vendredi 26 décembre 2014

How to update listview after inserting a record to database?

I have a problem with updating the listview after inserting a record to the database.


OnCreate, I load data from the database to the listview like that:



Cursor c = db.getAllCategory();
List<String> l = db.getItemByFilteredCategory();

//add total goals that match with each category
if (c.moveToFirst()) {
do {
int totalGoals = db.getMyGoalByCat(c.getInt(0)).getCount();
db.updateCategory(c.getInt(0), c.getString(1), c.getString(2), totalGoals);

} while (c.moveToNext());
}

//update category list
c = db.getAllCategory();

//add items to list
ListAdapter adapter = new SimpleCursorAdapter(this,
R.layout.custom_categorylist,
c,
new String[]{"_id", "categoryName", "categoryDescription", "totalGoals"},
new int[]{R.id.customViewCatId, R.id.customViewCategory, R.id.customViewCatDescription, R.id.customViewTargetNumber});

lv.setAdapter(adapter);


On the same activity, I have a button. When the button is clicked, I show a Dialog including 2 buttons: Create and Cancel.


If the Create button is clicked, I insert the new data to the database and dismiss the dialog.



btnAddCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_create_category);
dialog.setTitle("Create new category");
dialog.show();

Button btnCancel = (Button) dialog.findViewById(R.id.btnCancelCategory);
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});

final EditText etCatName = (EditText) dialog.findViewById(R.id.etCatName);
final EditText etCatDescription = (EditText) dialog.findViewById(R.id.etCatDescription);

Button btnCreate = (Button) dialog.findViewById(R.id.btnCreateCategory);
btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DBAdapter dbSub = new DBAdapter(getApplicationContext());
dbSub.openDB();
dbSub.insertCategory(etCatName.getText().toString(),etCatDescription.getText().toString(), 0);
dbSub.closeDB();

dialog.dismiss();
}
});
}
});


At that moment, I will be back on the main Activity with the listview. How can I get the listview update at this step?


Cheers,


Aucun commentaire:

Enregistrer un commentaire