Jack Roberts Jack Roberts - 4 months ago 8
Android Question

Android ListView position

I'm developing a web browser and I've just added bookmarks. I want to add a context menu to the list view to open and delete the bookmarks. I've got the code in place but when I tap the context menu it opens / deletes the top item. I'm really struggling to get it just right.

Any help will be greatly appreciated.



You could do something like this to get the ID of the selected bookmark:

public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    int position = info.position;
    Cursor selectedBookmark = (Cursor) mAdapter.getItem(position);

    int selectedBookmarkId = selectedBookmark.getInt(0); // index 0, assuming your first column is the ID

    / ...

After getting the ID, you can use it to delete the selected item from the DB:

long ret = mdb.delete("bookmark", "_id = ?", new String[]{Integer.toString(selectedBookmarkId)});