I want list view automatically update after deletion. I use adapter.notifyDataSetChanged() but it doesn't work for me
Here is my code
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Delete from database
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
EditData
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnDelete;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
ActionBar actionBar=getSupportActionBar();
actionBar.hide();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.4),(int)(height*.2));
btnDelete = (Button) findViewById(R.id.btnDelete);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
toastMessage("removed from database");
adapter.notifyDataSetChanged();
}
});
}
/**
* customizable toast
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListData
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
static ArrayAdapter adapter;
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
public void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
EditText editField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
editField = (EditText) findViewById(R.id.editText);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editField.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please Enter!", Toast.LENGTH_SHORT).show();
return;
}
String editText = editField.getText().toString();
AddData(editText);
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
And Layout are
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.tabian.saveanddisplaysql.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter any Thing"
android:layout_marginBottom="47dp"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="197dp"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:text="Add" />
<Button
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/btnAdd"
android:text="View Data" />
</LinearLayout>
</RelativeLayout>
edit_data_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="DELETE" />
</RelativeLayout>
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
After deletion instead of adapter.notifyDataSetChanged(); you can use the following code. It works fine for me:
adapter.remove(selectedName);
Related
I am trying to build an app using where entries are stored in a sqlitedatabase and the mainactivity contains recyclerview which displays the entries from the database. The problem is that the recyclerview displays only the first entry that has been entered.
For example if the first entry is "A" and the second entry is "B", the recyclerview only displays "A" and not "B"
The Code for the recyclerview adapter is given below :
RecyclerView Adapter
public class PasswordRecyclerViewAdapter extends RecyclerView.Adapter<PasswordRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<String> accounts;
private int position;
public PasswordRecyclerViewAdapter() {
}
public PasswordRecyclerViewAdapter(Context context, List<String> accounts) {
this.context = context;
this.accounts = accounts;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.linear_layout_simple_text, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.title.setText(accounts.get(position));
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = accounts.get(position);
Intent intent=new Intent(context, DetailsActivity.class);
intent.putExtra("Site",data);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return accounts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textview_title);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME="MyPrefs";
private RecyclerView recyclerView;
TextView emptyText;
PasswordRecyclerViewAdapter adapter;
List<String> collection;
List<String> myList=new ArrayList<String>();
PasswordDatabase passwordDatabase;
AdapterView.AdapterContextMenuInfo info;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
passwordDatabase = new PasswordDatabase(getApplicationContext());
myList = getArray();
collection = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.listViewID);
emptyText = (TextView)findViewById(R.id.text2);
adapter = new PasswordRecyclerViewAdapter(this, myList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
registerForContextMenu(recyclerView);
}
public List<String> getArray(){
/*SharedPreferences sp=this.getSharedPreferences(SHARED_PREFS_NAME,Activity.MODE_PRIVATE);
Set<String> set=sp.getStringSet("list",new HashSet<String>());
return new ArrayList<String>(set);*/
List accounts=passwordDatabase.getAcc();
return accounts;
}
}
In the function getArray() in MainActivity, the passwordDatabase.getAcc() returns the list of items stored in the sqlitedatabase. The code for the sqlitedatabase helper class is given below :
public final class PasswordDatabase extends SQLiteOpenHelper {
String data1;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserCredentials.db";
public static final String TABLE_NAME = "Credentials";
public static final String COLUMN_PASSWORD = "Password";
public static final String COLUMN_ACCOUNT = "Account";
public static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME;
private static final String TABLE_CREATE = "CREATE TABLE "
+ TABLE_NAME + " (" + COLUMN_ACCOUNT + " TEXT, " + COLUMN_PASSWORD
+ " TEXT,UNIQUE("+ COLUMN_ACCOUNT + "));";
public PasswordDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion){
onUpgrade(db, oldVersion, newVersion);
}
public void addCredentials(Context context,String account, String password){
SQLiteDatabase db = this.getWritableDatabase();
long newRowId=0;
Boolean flag=false;
ContentValues values = new ContentValues();
values.put(COLUMN_ACCOUNT, account);
values.put(COLUMN_PASSWORD, password);
newRowId = db.insert(TABLE_NAME, null, values);
}
public void deleteRow(String account){
SQLiteDatabase db=this.getWritableDatabase();
String whereClause=COLUMN_ACCOUNT+"=?";
String[] whereArgs=new String[] {account};
db.delete(TABLE_NAME,whereClause,whereArgs);
}
public void modify(String account,String pass){
SQLiteDatabase db=this.getWritableDatabase();
String sql="UPDATE "+ TABLE_NAME +" SET " +COLUMN_PASSWORD +" = " +pass + " WHERE "+ COLUMN_ACCOUNT +" = " + account;
db.execSQL(sql);
}
public int modifyCredentials(String account,String newPass){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_PASSWORD,newPass);
String whereClause=COLUMN_ACCOUNT + " =?";
String[] whereArgs=new String[]{account};
int update=db.update(TABLE_NAME,contentValues,whereClause,whereArgs);
return update;
}
public void deleteAllCredentials(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
public boolean checkdb(){
SQLiteDatabase db;
db=this.getWritableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM"+TABLE_NAME,null);
Boolean rowExists;
if (cursor.moveToFirst()){
rowExists=false;
}
else {
rowExists=true;
}
return rowExists;
}
public List<String> getAcc(){
SQLiteDatabase db=this.getReadableDatabase();;
List<String> collection=new ArrayList<>();
String acc=null;
Cursor c=null;
try{
String query="SELECT " + COLUMN_ACCOUNT + " FROM " + TABLE_NAME;
c=db.rawQuery(query,null);
if(c!=null){
if(c.moveToFirst()){
do{
acc=c.getString(c.getColumnIndex(COLUMN_ACCOUNT));
collection.add(acc);
}
while (c.moveToNext());
}
}
}
finally {
if(c!=null){
c.close();
}
if(db!=null){
db.close();
}
}
return collection;
}
public String getData(String data){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { COLUMN_ACCOUNT,COLUMN_PASSWORD
}, COLUMN_ACCOUNT + " = ?", new String[] { data },
null, null, null, null);
if (cursor!=null && cursor.moveToFirst()){
do{
data1=cursor.getString(1);
}while (cursor.moveToNext());
}
return data1;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.nitsilchar.hp.passwordStorage.activity.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/listViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#9fece2"
android:dividerHeight="0.5dp">
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:text="#string/main_xml_empty_text"/>
</RelativeLayout>
Can anyone help me for displaying all the entries stored in the database rather than only one entry
make sure your linear_layout_simple_text layout height to android:layout_height="wrap_content"
like below code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
I'm developing a tiny app that has a value in a textview set to 150,000 by default. Each month I reset the value back to the default. Every time I spend some of that amount, I open my app and enter the amount I spent and the details of what it was spent on.
What I did was create an offline database to store all the times I spent some of that amount, along with it's id and details. Each time I press the "spend" button, the total amount is reduced by the amount I have entered in the EditText.
I haven't implemented how I'll update the total amount yet, I believe I have to use something called sharedpreference number.
This is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button spendMoney = (Button)this.findViewById(R.id.spendMoney);
Button test = (Button)this.findViewById(R.id.test);
TextView totalTxt = (TextView) this.findViewById(R.id.totalTxt);
final EditText spendAmount = (EditText)this.findViewById(R.id.spendAmount);
// int totalAmount = Integer.parseInt(totalTxt.getText().toString());
final Paid_DB db = new Paid_DB(this);
spendMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.addPayment(new Payment(0, (Integer.parseInt(spendAmount.getText().toString())), "Test Details"));
}
});
//totalAmount = totalAmount - Integer.parseInt(spendAmount.getText().toString());
// totalTxt.setText(totalAmount);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(null, DetailsActivity.class);
startActivity(i);
}
});
XML file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"
android:layout_marginTop="53dp"
android:fontFamily="sans-serif"
android:text="Total:"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<EditText
android:id="#+id/spendAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="72dp"
tools:layout_editor_absoluteY="143dp"
android:layout_marginBottom="38dp"
android:layout_above="#+id/spendMoney"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/spendMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spend Money"
tools:layout_editor_absoluteX="115dp"
tools:layout_editor_absoluteY="215dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/totalTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_alignEnd="#+id/spendMoney"
android:layout_alignRight="#+id/spendMoney"
android:fontFamily="sans-serif"
android:text="150,000"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
tools:layout_editor_absoluteX="134dp"
tools:layout_editor_absoluteY="358dp"
android:layout_marginBottom="90dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/spendMoney"
android:layout_alignStart="#+id/spendMoney" />
This is the object I enter into the offline database, containing the id, the amount spent, and details of the payment:
public class Payment {
private int id;
private int amount;
private String details;
public Payment(){}
public Payment(int id, int amount, String details) {
this.id = id;
this.amount = amount;
this.details = details;
}
public Payment(int id, int amount) {
this.id = id;
this.amount = amount;
}
public Payment(int amount, String details) {
this.amount = amount;
this.details = details;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
} }
This is the offline database:
ublic class Paid_DB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Payments_DB";
// Contacts table name
private static final String PAYMENT_TABLE = "PaymentTable";
// Contacts Table Columns names
private static final String PAY_ID = "id";
private static final String PAY_AMOUNT = "amount";
private static final String PAY_DETAILS = "details";
Paid_DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PAYMENT_TABLE + "("
+ PAY_ID + " INTEGER PRIMARY KEY," + PAY_AMOUNT + " INTEGER,"
+ PAY_DETAILS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + PAYMENT_TABLE);
onCreate(db);
}
public void addPayment(Payment payment){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PAY_AMOUNT, payment.getAmount());
values.put(PAY_DETAILS, payment.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(PAYMENT_TABLE, null, values);
db.close();
}
void addListItem(ArrayList<String> listItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < listItem.size(); i++) {
Log.e("vlaue inserting==", "" + listItem.get(i));
values.put(PAY_AMOUNT, listItem.get(i));
db.insert(PAYMENT_TABLE, null, values);
}
db.close(); // Closing database connection
}
Cursor getListItem() {
String selectQuery = "SELECT * FROM " + PAYMENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}}
And finally, this is the details activity, it contains a list view that stores and displays all the payments that have been made:
public class DetailsActivity extends AppCompatActivity {
ArrayList<String> detailsListArrayList;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
lv = (ListView) findViewById(R.id.listView);
detailsListArrayList = new ArrayList<>();
detailsListArrayList.add("Item1");
detailsListArrayList.add("Item2");
detailsListArrayList.add("Item3");
detailsListArrayList.add("Item4");
detailsListArrayList.add("Item5");
Paid_DB db = new Paid_DB(this);
db.addListItem(detailsListArrayList);
Cursor cursor = db.getListItem();
Log.e("count", " " + cursor.getCount());
if (cursor != null) {
cursor.moveToNext();
do {
Log.e("value==", "" + cursor.getString(1));
} while (cursor.moveToNext());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
detailsListArrayList );
lv.setAdapter(arrayAdapter);
}
}
XML file:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.paid.DetailsActivity">
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
Every time I click on the "test" button, the app crashes. And every time I try to add a new entry using the "spend" button, the app also crashes. What did I do wrong?
What I can tell from here (without the error log) is:
1) your app crashes when pressing the test-button because you are starting an activity there without passing a contextobject. Try this:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
startActivity(i);
}
2) The spend button tries to add a new payment entry to your database. But in your database schema , you declare the PAY_ID as a primary key. Later in your addPayment() you are just passing the PAY_AMOUNT and PAY_DETAILS, so you are missing the PAY_ID which seems to lead to a crash.
EDIT: something like this should return all the payments as an ArrayList (may Contain bugs, just wrote it in this editor).
public ArrayList<Payment> getAllPayments() {
ArrayList<Payment> result = new ArrayList<>();
Cursor c = db.query("PAYMENTS",new String[]{"PAY_ID","PAY_AMOUNT","PAY_DETAIL"},null,null,null,null,null); ;
c.moveToFirst();
while(! c.isAfterLast())
{
int s1=c.getInt(0);
int s2=c.getInt(1);
String s3=c.getString(2);
results.add(new Payment(s1,s2,s3));
c.moveToNext();
}
return results;
}
To update your ListView, you should have a closer look a this link, that explains how to work with ListViews and a custom ListView adapter Custom Adapter for List View
Hello everybody i m building an android application which has timepicker. what i want is that i want to update the database when user clicks the save button twice. Please guide me how to do that. Now my application crashes because no updation of database takes place.
TimeTable.java
public class Monday extends FragmentActivity implements TimePickerFragment.TimePickerDialogListener {
EditText et1, et2, et3;
TextView tvm;
LinearLayout llm;
int fhour, fmin, thour, tmin, j;
private int cnt = 0;
View vi[] = new View[100];
TimeTableDbHelper db;
String txt,fmeridien,tmeridien,ftime,ttime;
private static final int START_TIME_PICKER_ID = 1;
private static final int END_TIME_PICKER_ID = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_monday);
tvm = (TextView) findViewById(R.id.tvm);
llm = (LinearLayout) findViewById(R.id.llm);
db = new TimeTableDbHelper(this);
cnt = db.check("timetableM");
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
LinearLayout mn = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, mn, false);
vi[i] = view;
mn.addView(view);
et1 = (EditText) vi[i].findViewById(R.id.txtTime);
et1.setText(db.rd1(i,1));
//Log.i("Monday", "Database read" + db.read(2) + db.read(3));
et2 = (EditText) vi[i].findViewById(R.id.txtTime2);
et2.setText(db.rd1(i,2));
//Log.i("Monday", "Database read" + db.read(4) + db.read(5));
et3 = (EditText) vi[i].findViewById(R.id.txtSet);
et3.setText(db.rd1(i,3));
}
j = i;
} else {
j = 0;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_monday, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void setTime(View v) {
LinearLayout main = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, main, false);
view.setTag(j);
main.addView(view);
vi[j] = view;
}
public void setTime2(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(START_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
public void setTime3(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(END_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute) {
Log.i("TimePicker", "Time picker set from id " + id + "!");
if (id == START_TIME_PICKER_ID) {
et1 = (EditText) vi[j].findViewById(R.id.txtTime);
fmin = minute;
if(hourOfDay <= 12) {
fhour = hourOfDay;
fmeridien = "AM";
} else {
fhour = hourOfDay-12;
fmeridien = "PM";
}
ftime =fhour + ":" + fmin + fmeridien;
et1.setText(ftime);
} else {
et2 = (EditText) vi[j].findViewById(R.id.txtTime2);
tmin = minute;
if(hourOfDay < 12) {
thour = hourOfDay;
tmeridien = "AM";
} else {
thour = hourOfDay-12;
tmeridien = "PM";
}
ttime = thour + ":" + tmin +tmeridien;
et2.setText(ttime);
}
}
public void Save(View v)
{
int position = (int) v.getTag();
if(position<j);
else {
et3 = (EditText) vi[j].findViewById(R.id.txtSet);
txt = et3.getText().toString();
Log.i("Position", "Value is " + position);
db.write1(j, ftime, ttime, txt);
Toast.makeText(this, "Successfully saved", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
int day = c.get(Calendar.DAY_OF_WEEK);
int value;
if(fmeridien=="AM") value=0;
else value=1;
c.set(Calendar.DAY_OF_WEEK,day);
c.set(Calendar.AM_PM, value);
c.set(Calendar.HOUR, fhour);
c.set(Calendar.MINUTE, fmin);
c.set(Calendar.SECOND,0);
Intent i = new Intent("com.example.annu.sheduler.DisplayNotification");
//---assign an ID of 1---
i.putExtra("NotifID", j);
i.putExtra("text",txt);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), j, i, 0);
j++;
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), displayIntent);}
}
}
activity_monday.xml
<LinearLayout android:id="#+id/llm"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.annu.sheduler.Monday"
android:background="#ffffa751"
android:label="Monday">
<TextView
android:id="#+id/tvm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setTime"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:text="Create a schedule"
android:textStyle="bold"
android:textSize="24sp"/>
</LinearLayout>
activity_timepicker.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txtTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="From"
android:onClick="setTime2"/>
<EditText
android:id="#+id/txtTime2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="To"
android:onClick="setTime3"/>
<EditText
android:id="#+id/txtSet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:hint="Description!!!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="Save"
android:minHeight="0dp"
android:minWidth="20dp"/>
</LinearLayout>
TimeTableDbHelper.java
public class TimeTableDbHelper extends SQLiteOpenHelper {
public static final String TABLE_NAMEM = "timetableM";
public static final String COLUMN_NO1 = "c_no1";
public static final String COLUMN_FROM_TIME1 = "FTIME1";
public static final String COLUMN_TO_TIME1 = "TTIME1";
public static final String COLUMN_DESC1 = "Description1";
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "TimeTable.db";
public TimeTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_TIME_TABLE1 = "CREATE TABLE " + TABLE_NAMEM + " (" +
COLUMN_NO1 + " INTEGER PRIMARY KEY, " +
COLUMN_FROM_TIME1 + " STRING NOT NULL," +
COLUMN_TO_TIME1 + " STRING NOT NULL," +
COLUMN_DESC1 + " TEXT NOT NULL" +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TIME_TABLE1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMEM);
onCreate(sqLiteDatabase);
}
public void write1(int column_no, String ftime, String ttime, String desc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NO1, column_no);
values.put(COLUMN_FROM_TIME1, ftime);
values.put(COLUMN_TO_TIME1, ttime);
values.put(COLUMN_DESC1, desc);
Boolean res = CheckIsDataAlreadyInDBorNot(TABLE_NAMEM, COLUMN_NO1, column_no);
if (res == false) db.insert(TABLE_NAMEM, null, values);
else db.update(TABLE_NAMEM, values, null, null);
db.close();
}
public int check(String tname) {
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM " + tname;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public String rd1(int c_no, int col) {
String selectQuery = "SELECT * FROM " + TABLE_NAMEM + " WHERE " + COLUMN_NO1 + " = " + c_no;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = "";
if (cursor.moveToFirst()) {
// get the data into array,or class variable
do {
data = cursor.getString(col);
//Log.i("TimeTableDbHelper", "Value read " + cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
return data;
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, int fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
}
As stated here
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[]):
Returns:
the number of rows affected
So you can do just:
if (db.update(TABLE_NAMEM, values, null, null) == 0)
db.insert(TABLE_NAMEM, null, values);
db.close();
I have created database following this tutorial, and I have created one button in main activity which will take users to another activity where they would add some new items. But I don't know how would I do this with ArrayList because I want to add new items in ListView. I want something like this to have in my application. Any help would be appricieated.
Here's the code of DataBase:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "itemManager";
// Contacts table name
private static final String TABLE_ITEMS = "items";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_PRICE = "price";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_PRICE + " TEXT" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new item
void addItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle()); // Title Name
values.put(KEY_PRICE, item.getPrice()); // Price
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
// Getting item
Item getItem(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
KEY_TITLE, KEY_PRICE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Item item = new Item(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return item
return item;
}
// Getting All Items
public List<Item> getAllItems() {
List<Item> itemsList = new ArrayList<Item>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Item item = new Item();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setTitle(cursor.getString(1));
item.setPrice(cursor.getString(2));
// Adding contact to list
itemsList.add(item);
} while (cursor.moveToNext());
}
// return items list
return itemsList;
}
// Updating single item
public int updateItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, item.getTitle());
values.put(KEY_PRICE, item.getPrice());
// updating row
return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
}
// Deleting single item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(item.getID()) });
db.close();
}
// Getting items Count
public int getItemsCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
and here is the code of MainActivity:
public class MainActivity extends BaseActivity {
Button addItem;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);
// inflate the custom activity layout
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);
frameLayout.addView(activityView);
// Setting toolbar
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
DatabaseHandler db = new DatabaseHandler(this);
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
}
}
Here's my Main Activity layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<Button
android:id="#+id/button1"
style="#style/MyCustomButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="#string/button" />
<ListView
android:id="#+id/list"
android:layout_margin="5dp"
android:layout_below="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_centerHorizontal="true"
android:divider="#color/list_divider_row"
android:dividerHeight="10.0sp"
android:listSelector="#drawable/list_row_selector" >
</ListView>
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/listView1"
android:layout_alignRight="#+id/listView1"
android:layout_below="#+id/app_bar"
android:padding="10dp" >
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
android:text="Items"
android:textColor="#474747"
android:textSize="16sp" />
<TextView
android:id="#+id/item_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:layout_toRightOf="#+id/item_text"
android:text="(2)"
android:textColor="#474747"
android:textSize="14sp" />
<TextView
android:id="#+id/total_amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="Rs. 5700"
android:textColor="#000000"
android:textSize="20dp" />
</RelativeLayout>
</RelativeLayout>
In a nutshell, you need to pass the "result" of adding an item back to the main activity. Then, if there was an item added, you should call your adapter to update the adapter data.
// Your previous code
addItem = (Button) findViewById(R.id.button1);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivityForResult(intent, ADD_ITEM_REQ_CODE);
}
});
// Then handle the result
public void onActivityResult(int reqCode, int resultCode, Intent data){
if (reqCode == ADD_ITEM_REQ_CODE && resultCode == RESULT_OK){
// get your ListView adapter and update data
mListAdapter.notifyDataSetChanged();
}
}
Your second activity, the one that adds an item should call setResult(RESULT_OK) when the item was added successfully and setResult(RESULT_CANCELLED) otherwise.
There some other things with your code, for instance, where do you populate your ListView? Normally, you would get the instance though a findViewById and set an adapter to that ListView, with the corresponding data.
Honestly, I think you should have a look to the tutorials again, specially these:
http://developer.android.com/training/basics/intents/result.html
http://developer.android.com/guide/topics/ui/layout/listview.html
I am new to Android and I am making a simple Log in/Register app. At the moment my problem is that the SQLite database create is not executing meaning that it wont make my table. I have made:
Register.java
public class Register extends Activity implements View.OnClickListener {
EditText insertUsername, insertName, insertPassword, insertFinal;
Button create;
LoginDBAdapter loginHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
}
#Override
protected void onDestroy(){
super.onDestroy();
close();
}
private void close() {
loginHandler.close();
}
private void open() {
loginHandler = new LoginDBAdapter(this);
loginHandler.open();
}
public void onClick(View v) {
String username = insertUsername.getText().toString();
String name = insertName.getText().toString();
String password = insertPassword.getText().toString();
String confirm = insertFinal.getText().toString();
//Validation for the fields
// check if any of the fields are vaccant
if (username.equals("") || password.equals("") || confirm.equals("")) {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirm)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
} else {
// Save the Data in Database
loginHandler.register(username, name, password);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
finish();
}
}
}
LoginAdapter.
public class LoginDBAdapter {
private SQLiteDatabase db;
private DataBaseHelper myHelp;
// Labels table name
public static final String TABLE_NAME = "Users";
private static final String DATABASE_NAME = "login.db";
// Labels Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_Username = "Username";
public static final String KEY_name = "Name";
public static final String KEY_password = "Password";
// property help us to keep data
public int User_id;
public String Username;
public String Name;
public String Password;
public static final String DATABASE_CREATE = "create table "+ TABLE_NAME+
"(" + KEY_ID + " integer primary key autoincrement ,"
+ KEY_Username + "Username text not null, "
+ KEY_name + "Name text not null, "
+ KEY_password +"Password text not null);";
private final Context context;
public LoginDBAdapter(Context data) {
this.context = data;
myHelp = new DataBaseHelper(context);
}
public LoginDBAdapter open(){
db = myHelp.getWritableDatabase();
return this;
}
public void close(){
myHelp.close();
}
public long register(String username, String name, String password){
ContentValues newUser = new ContentValues();
newUser.put(KEY_Username, username);
newUser.put(KEY_name, name);
newUser.put(KEY_password, password);
//Inserting put information into a new row into Users table
return db.insert(TABLE_NAME, null, newUser);
}
public String authLogin(String username) {
Cursor cursor = db.query("Users", null, " Username= ?", new String[]{username}, null, null, null);
if (cursor.getCount() < 1) {
cursor.close();
return "Username does not exist";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("Password"));
cursor.close();
return password;
}
private static class DataBaseHelper extends SQLiteOpenHelper {
private static final int version = 1;
public DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, version);
}
//This is called if no database exists and DataBaseHelper will create a new one
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("create table "+ TABLE_NAME+
"(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ KEY_Username + "Username text not null, "
+ KEY_name + "Name text not null, "
+ KEY_password +"Password text not null)");
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
#Override
public void onUpgrade(SQLiteDatabase create_db, int oldVersion, int newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
//Destroy all data
create_db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
// Create a new one.
onCreate(create_db);
}
}
}
What have I done wrong? I had the project at one point pass the username, name and password passed to register but could not insert into table Users because it doesnt exist. I ran it through Android Device Monitor
No table: Users
There is a problem with your SQL statement.
+ KEY_Username + "Username text not null, "
This will render as
"UsernameUsername text not null, "
So you should probably change it to:
+ KEY_Username + " text not null, "
The same mistake is in other lines as well.
I think you are never calling this method
private void open() {
loginHandler = new LoginDBAdapter(this);
loginHandler.open();
}
from the Register class.
I suggest to change the onCreate method as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
open();
}
use this code.it will help you out to create a table in sqlite as well as you can store the Registeration details too
Register.java
public class Register extends Activity implements View.OnClickListener {
EditText insertUsername, insertName, insertPassword, insertFinal;
Button create;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_register);
insertUsername = (EditText) findViewById(R.id.insertUsername);
insertName = (EditText) findViewById(R.id.insertName);
insertPassword = (EditText) findViewById(R.id.insertPassword);
insertFinal = (EditText) findViewById(R.id.insertFinal);
}
public void onClick(View v) {
String username = insertUsername.getText().toString();
String name = insertName.getText().toString();
String password = insertPassword.getText().toString();
String confirm = insertFinal.getText().toString();
//Validation for the fields
// check if any of the fields are vaccant
if (username.equals("") || password.equals("") || confirm.equals("")) {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if (!password.equals(confirm)) {
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
} else {
// Save the Data in Database
Intent intent1=new Intent(Register.this,LoginDBAdapter.class);
Bundle userdata=new Bundle();
userdata.putString("username",username);
userdata.putString("name",name);
userdata.putString("password",password);
userdata.putString("confirm",confirm );
intent1.putExtras(userdata);
startActivity(intent1);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
}
}
}
LoginDBAdapter.java
public class LoginDBAdapter extends Activity {
TextView text;
SQLiteDatabase mydb;
String username,name,password;
private static String DBNAME = "login.db"; // THIS IS THE SQLITE DATABASE FILE NAME.
private static String TABLE = "Users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Bundle userdetails=getIntent().getExtras();
username= userdetails.getString("username");
name=userdetails.getString("name");
password=userdetails.getString("password");
text=(TextView)findViewById(R.id.txthead);
createTable();
insertIntoTable(username,name,password);
}
public void createTable(){
try
{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, Username TEXT,Name TEXT, Password TEXT);");
mydb.close();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG).show();
}
}
#SuppressLint("DefaultLocale")
public void onsearchclick(View view)
{
// Toast.makeText(getApplicationContext(), "subval of"+ subval+""+subval1+"",Toast.LENGTH_SHORT).show();
showTableValues();
}
public void insertIntoTable(String username,String name,String password){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(Username,Name,Password) VALUES('"+username+"','"+name+"','"+password+"')");
mydb.close();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), ""+e.toString()+"", Toast.LENGTH_LONG).show();
//System.out.println(""+e.toString()+"");
}
}
The showTableValues will show the last entered username and password and name of the person
public void showTableValues()
{
try
{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor cursor=mydb.rawQuery("SELECT * FROM Users", null);
int x = cursor.getCount(); //this will return number of records in current cursor
Toast.makeText(getApplicationContext(), ""+x+"",Toast.LENGTH_SHORT).show();
if ( x == 0 )
{
//No rows are inserted in table
}
else
{
try
{
cursor.moveToFirst();
do {
String username=cursor.getString(cursor.getColumnIndex("Username")).toString();
String name=cursor.getString(cursor.getColumnIndex("Name")).toString();
String password=cursor.getString(cursor.getColumnIndex("Password")).toString();
String tempString="User Name: "+username.toString();
String tempString1="Name: "+""+name.toString();
String tempString2="Password: "+""+password.toString();
TextView text=(TextView)findViewById(R.id.txthead);
text.setText(tempString);
text.append(tempString1);
text.append(tempString2);
} while (cursor.moveToNext());
}
finally
{
cursor.close();
mydb.close();
}
// }
}
}
catch( Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
fragment_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/insertFinal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/final1"
android:layout_alignBottom="#+id/final1"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="Confirm Password" >
</EditText>
<EditText
android:id="#+id/insertUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10"
android:hint="Enter user name" />
<TextView
android:id="#+id/txtusername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/insertUsername"
android:layout_alignBottom="#+id/insertUsername"
android:layout_alignParentLeft="true"
android:text="User Name:" />
<Button
android:id="#+id/Register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="125dp"
android:padding="30dp"
android:text="Register"
android:onClick="onClick"/>
<TextView
android:id="#+id/final1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Register"
android:layout_alignParentLeft="true"
android:layout_marginBottom="78dp"
android:text="Confirm password" />
<TextView
android:id="#+id/Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/insertFinal"
android:layout_alignParentLeft="true"
android:layout_marginBottom="17dp"
android:text="Password" />
<EditText
android:id="#+id/insertPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/Password"
android:layout_alignBottom="#+id/Password"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="enter password" />
<EditText
android:id="#+id/insertName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/insertPassword"
android:layout_alignParentRight="true"
android:ems="10"
android:hint="Enter Name:" />
<TextView
android:id="#+id/txtname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txtusername"
android:layout_alignTop="#+id/insertName"
android:text="Name:" />
</RelativeLayout>
activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show"
android:onClick="onsearchclick" ></Button>
<TextView
android:id="#+id/txthead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/show" />
</RelativeLayout>
in Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.login"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Register"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.login.LoginDBAdapter" />
</application>
</manifest>