keysersoze
keysersoze

Reputation: 2572

Getting ExpandableListView's selected item from ContextMenu

Hi I have a problem with getting the id of ExpandableListView's item from ContextMenu which I need to delete the entry from my database (im using content provider).

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, "Edit");
    menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, "Remove");
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
    switch (item.getItemId()) {
        case MENU_EDIT:
            editEntry(info.id);
            return true;
        case MENU_REMOVE:
            deleteEntry(info.id);
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

private void deleteEntry(long id) {
    Uri uri = Uri.parse(DatabaseManager.CONTENT_URI + "/" + id);
    getActivity().getContentResolver().delete(uri, null, null);
}

The ContextMenu is showing but when i click on "Remove" nothing happens. Could you tell me what should i do?

Upvotes: 2

Views: 1313

Answers (1)

sleidig
sleidig

Reputation: 1390

Because ExpandableListView has two levels - groups and children - the "ID" is difficult to interpret directly.

You need to decompose the information from ExpandableListContextMenuInfo into a group position and child position.

With these two values you can then retrieve the selected item from the Adapter (here this.exandableListAdapter) you used as a data source for your ExpandableListView. The object that the Adapter's getChild() returns can be converted to whatever (custom) type you initially put into the Adapter:

ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo();
int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);
MyItemClass item =(MyItemClass) this.expandableListAdapter.getChild(groupPos, childPos);

From this item you should easily be able to get the id in your database or whatever specific information you need.

Upvotes: 3

Related Questions