onContextItemSelected - item id NullPointerException

时间:2013-08-31 11:47:58

标签: android contextmenu

我有自定义适配器的ListView。直到现在我都有长按的上下文菜单。并通过此

重新执行此操作
 getListView().setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
    {

        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
            //To register the button with context menu.
                            registerForContextMenu(getListView());
                            openContextMenu(getListView());

        }
    });

仅限于此

registerForContextMenu(getListView());

在此更改之前它可以正常工作,但现在我在info.id处有NullPointerException,我不知道如何修复它。谢谢你的回复。

 @Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    Intent i;
    Log.d("item id", String.valueOf(item.getItemId()));
    switch (item.getItemId()) {

    case R.id.spotreba:    
         i = new Intent(this, SpotrebaActivity.class);
         i.putExtra("idAuta", info.id);
         startActivityForResult(i, REQUEST_ADD_AUTO);
         return true;
         .
         .
         .

1 个答案:

答案 0 :(得分:0)

您应该在活动中使用ListView注册上下文菜单,而不是在您创建的内部类(onItemClickListener)中注册。

将其写为..

registerForContextMenu(getListView());
getListView().setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() 
    {

        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {
               openContextMenu(getListView());
        }
    });