javaandroidnullpointerexceptionexpandablelistviewandroid-contextmenu

How to delete an item from ExpandableListView on long click with a ContextMenuItemSelected?


I am trying to delete an item from an ExpandableListView using a context menu. I am running into a null pointer exception. Please help me solve this issue. Below is my code:

@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
        super.onContextItemSelected(item);
        switch(item.getItemId())
        {
            case R.id.deleteItem:
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                    int position = info.position;
                    //this is my ArrayList                    
                    postList.remove(position);
                    Toast.makeText(getActivity().getApplicationContext(), "Deleted an item", Toast.LENGTH_LONG).show();
                    listAdapter.notifyDataSetChanged();
                break;
            case R.id.editItem:
                break;
        }

        return true;
    }

Solution

  • Type of ContextMenuInfo is wrong, items in Expandablelistview have 2 position values,

        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition); 
        int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);