开发者

Deleting row from database using _id column in context menu from ListView

I have a listview which is popula开发者_开发问答ted 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.


When you say it isn't working, what isn't working? Does it not delete the entry? Does it not display the updated list? How are you deleting the row? Can you share some more code?

In general, id is generally the _id of the database (if you use the standard conventions). Are you using your own content provider? You need to notify system that the database changed so it can be requeried - this is typically done if you followed the ContentProvider samples from the SDK (look at notifyChange), and if you use a managed query.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜