Вопрос

I am getting NullPointerException in the code for contextmenu. here is the onCreateContextmenu Method

public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, MENU_EDIT, 0, "Edit");
    menu.add(0, MENU_DELETE, 0, "Delete");
}

I am getting the error in the line long buttonId = info.id; in the code below

public boolean onContextItemSelected(MenuItem item) {

   AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    long buttonId = info.id;
    switch (item.getItemId()) {
        case MENU_EDIT:
            function1(buttonId);
            break;
        case MENU_DELETE:
            function2(buttonId);
            break;
    }
    return true;
}

Can some one help me fix this

Это было полезно?

Решение

view isn't passed to onContextItemSelected and

AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); long buttonId = info.id;

This code doesn't help because menuInfo is null when view is a button. The Android doc says "menuInfo Extra information about the item for which the context menu should be shown. This information will vary depending on the class ofv". When v is a ListView menuInfoapproach is fine. When it is a Button, it doesn't work.

In onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo), the View v is the button that produced the context menu. Copyv to a global View varaiable and use that where you need to have the view of the button that produced the context menu.

How to get the Button view which triggered a Context Menu?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top