我在向数据库中插入记录后更新 ListView 时遇到问题。
在创建时,我将数据从数据库加载到 ListView 中:
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);
在同一个 Activity 中,我有一个按钮。单击该按钮后,我会显示一个包含 2 个按钮的对话框:创建和取消。
如果单击“创建”按钮,我会将新数据插入数据库并关闭对话框。
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();
}
});
}
});
在那一刻,我将回到带有 ListView 的主 Activity。如何在这一步获取 ListView 更新?
干杯,
最佳答案
要更新列表中的数据,您必须调用 adapter.notifyDataSetChanged()。
关于android - 向数据库插入记录后如何更新 ListView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27655862/