I have a listview which is populated by a SimpleCursorAdapter that is binding data to the view from a cursor from a sqlite database. I would like to have a context menu option to delete the a list item when it is long pressed, so I register the ListView for a context menu by calling registerForContextMenu(historyListView). I’ve been trying to remove the row from the database by getting the row id in OnCreateContextMenu and storing it as a private field called lastSelectedId, then if the remove context item is selected in OnContextItemSelected, removing the row from the database by checking the _id column against lastSelectedId.
This isn’t working.
So –
(1.) is the row as given by
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
lastSelectedId = info.id;
the same as the _id column in the database?
and (2.) if not, how else can I delete the item in onContextItemSelected() based on the _id of the row in the database?
EDIT: Sorry about not explaining why this approach wasn’t working more in-depth: What happens is that nothing happens when I attempt to delete the row: I call mDB.delete(DB_TABLENAME,"_id=" + lastSelectedId, null); on the database and then I call bookmarksListAdapter.notifyDataSetChanged(); on my SimpleCursorAdapter. Then I see no change in the entries in my listview, which differs from my expected behavior that the row which I called remove on will disappear.
Figured it out. I needed to re-do the cursor after the database was changed (for some reason I had thought that this would be done automatically – my mistake)
bookmarksDbCursor.requery()fixed it for me.