经过对数据库的修改我如何刷新我的ListView? [英] How do I refresh my ListView after the database changes?
问题描述
我想在Android应用程序管理一个简单的列表。该列表的内容被保持在SQLite数据库。当用户选择并保持在一个特定的行,显示上下文菜单与一个删除选项。当他们选择删除,该行从数据库中删除,但认为不会刷新。当我回到了应用程序,并在回来后,相应的行已被删除。所以,我知道行被删除,它只是一个不刷新的ListView。
I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh.
下面是$相关位c $ C ...
Here are the relevant bits of code...
在onCreate方法...
In the onCreate method...
SQLiteDatabase db = tasks.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,
new String[] { _ID, TITLE, DETAILS, },
null, null, null, null, TITLE + " DESC");
startManagingCursor(cursor);
ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[] {TITLE},
new int[] { android.R.id.text1}
));
在onContextItemSelected方法...
In the onContextItemSelected method...
switch(item.getItemId()) {
case 0:
SQLiteDatabase db = tasks.getWritableDatabase();
ListView lv = (ListView) findViewById(R.id.list);
SimpleCursorAdapter adapter = (SimpleCursorAdapter) lv.getAdapter();
db.delete(TABLE_NAME, "_ID=?", new String[] {adapter.getCursor().getString(0)});
adapter.notifyDataSetChanged(); // Not working, clears screen and doesn't reload
return true;
}
return super.onContextItemSelected(item);
我在想什么?
What am I missing?
谢谢!
推荐答案
摆脱 notifyDataSetChanged()
并调用重新查询()<的/ code>在
光标
。 这里是证明这是一个示例项目。
Get rid of the notifyDataSetChanged()
and call requery()
on your Cursor
. Here is a sample project demonstrating this.
这篇关于经过对数据库的修改我如何刷新我的ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!