Reputation: 20409
I do something like below:
public class WhitelistActivity extends ListActivity {
private DbAdapter dbHelper;
private SimpleCursorAdapter adapter;
private Cursor recordsCursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.whitelist);
dbHelper = new DbAdapter(this);
dbHelper.open();
recordsCursor = dbHelper.fetchWhitelistRecords();
startManagingCursor(recordsCursor);
String[] from = new String[]{DbAdapter.KEY_W_SENDER};
int[] to = new int[]{R.id.text1};
adapter = new SimpleCursorAdapter(this, R.layout.whitelist_row, recordsCursor, from, to);
setListAdapter(adapter);
...
@Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case CONTEXT_MENU_DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
dbHelper.deleteWhitelistRecord(info.id);
adapter.changeCursor(recordsCursor);
adapter.notifyDataSetChanged();
return true;
}
return super.onContextItemSelected(item);
}
However, when context menu is called and item is deleted, it is not reflected on the list view. What am I missing?
Upvotes: 0
Views: 888
Reputation: 39406
When you change your cursor, you need to update its content. The simplest and recommended way is to create a new cursor (if possible in a Loaded).
recordsCursor = dbHelper.fetchWhitelistRecords();
adapter.changeCursor(recordsCursor);
It is not necessary to notifyDataSetChanged.
Upvotes: 0
Reputation: 8641
The Cursor isn't updated until you requery the database. startManagingCursor doesn't do this automatically. adapter.notifyDataSetChanged() "updates" the ListView, but since the Cursor hasn't changed, nothing happens.
What you should really consider doing is encapsulating your database in a ContentProvider and then using CursorLoader to manage the Cursor and requeries. If you do this, life becomes much simpler. See Loading Data in the Background to learn how to set up CursorLoader. Encapsulating a database in a ContentProvider is also straightforward, see the API guide Creating a Content Provider.
Upvotes: 2