4

I am using this code to get the Clicked Item position on the Context Menu:

public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int index = info.position;
}

as suggested here:

Android: How to find the position clicked from the context menu

But i get NullPointerException at line:

 int index = info.position;

why is it so?

EDIT

I have 2 registered Views for the contextMenu like this:

button1.onClick(view v){
registerForContextMenu(v);
openContextMenu(v);
}

button2.onClick(view v){
registerForContextMenu(v);
openContextMenu(v);
}

then depending on v.getId() i populate the menu.

Community
  • 1
  • 1
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226

2 Answers2

0

You can use directly:

EDITED BEGIN

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info;
    try {
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        // If the menu object can't be cast, logs an error.
        Log.e("MENU", "bad menuInfo", e);
        return;
    }
    position = sectionAdapter.getIndexForPosition(info.position);
    menu.setHeaderTitle("");
    String[] menuItems = { "item1","item2","item3","item4" };
    for (int i = 0; i < menuItems.length; i++) {
        menu.add(Menu.NONE, i, i, menuItems[i]);
    }
}

EDITED END

public boolean onContextItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    int position = item.getItemId();
    switch (position) 
    {

        case 0:
        break;
        .
        .
        .
        default:
        break;
    }
}

Hope it will help you.

Rushabh Patel
  • 3,052
  • 4
  • 26
  • 58