开发者

Android - ResourcesNotFoundException inside onContextItemSelelcted

I am trying to create an app which displays the thumbnails of photos in a folder. I am using GridView for this purpose. I have been able to successfully create the view and populate it with images. However, when I tried to implement a context menu option to delete a selected photo, I get ResourcesNotFoundException.

In the code below I have indiciated where exactly the error occurs. Any pointers would be greatly appreciated.

Thank you!

Joe

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos);
    this.gridView = (GridView) findViewById(R.id.gridView);
    imageArrayAdapter = new ImageArrayAdapter(this, R.layout.thumb_item, photosList);
    this.gridView.setAdapter(imageArrayAdapter);
    registerForContextMenu(gridView);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("File Options");

    menu.add(Menu.NONE, 1, Menu.NONE, R.string.delete).
    setIcon(R.drawable.delete).
    setAlphabeticShortcut('d');
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    try {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        // Works correctly
        Toast.makeText(t开发者_C百科his, item.getId(), Toast.LENGTH_SHORT).show();

        // Causes ResourcesNotFoundException
        Toast.makeText(this, item.getId(), Toast.LENGTH_SHORT).show();

        // Works well, prints false
        Toast.makeText(this, "" + (info == null), Toast.LENGTH_SHORT).show();

        // Causes ResourcesNotFoundException
        Toast.makeText(this, info.position, Toast.LENGTH_SHORT).show();
    } catch(Exception ignore) {
        Log.e("onContextItemSelected", ignore);
    }
    return(super.onOptionsItemSelected(item));
}


It sounds like Toast is raising a resource exception because the ID you're passing it (item.getId() or info.position) is not a valid string resource in your R array.

The prototype for ContextMenu.add() is:

add(int groupId, int itemId, int order, int titleRes)

so you're setting "itemId" to 1, then trying to use that same id as a string resource ID later.

You might be able to make itemId be the same as the title resource ID in all your menu items -- eg:

add(Menu.NONE, R.string.delete, Menu.NONE, R.string.delete);

I don't think that would be recommended though, as it confuses two different types of IDs -- menu item selection IDs, and string resource IDs.

Instead, you can have a separate ID space for menu items and switch() on them in your listener, selecting appropriate string resource IDs or other actions you need to take on selection.

Or use MenuItem.getTitle() in your listener if all you need is the text of the item.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜