Android AlertDialog框WindowManager $BadTokenException问题

前端之家收集整理的这篇文章主要介绍了Android AlertDialog框WindowManager $BadTokenException问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下代码进行上下文菜单,然后如果用户选择删除,将出现对话按摩.
infos.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){
            //@Override
            public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("Context Menu");
                menu.add(0,CONTEXT_EDIT,"Edit Item");
                menu.add(0,CONTEXT_DELETE,1,"Delete Item");
            }
});

public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        final Long _id = menuInfo.id;
        //selected_row = menuInfo.position;

        // To get the id of the clicked item in the list use menuInfo.id
        switch (item.getItemId()) {
            case CONTEXT_EDIT:
                addEditRes(_id);
                break;
            case CONTEXT_DELETE:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Are you sure you want to delete?")
                       .setCancelable(false)
                       .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog,int id) {
                               infoDataHelper.deleteRes(_id);  
                               model = infoDataHelper.getCursor(addType);
                               adapter.changeCursor(model);
                           }
                       })
                       .setNegativeButton("No",int id) {
                                dialog.cancel();
                           }
                       });
                AlertDialog alert = builder.create();   
                alert.show();
                break;
            default:
                return super.onContextItemSelected(item);

        }
        adapter.notifyDataSetChanged();
        return true;
}

但是,只要我选择删除,它会给出以下错误.

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

我的代码有什么问题?

解决方法

我相信这个问题可能在这一行上:
AlertDialog.Builder builder = new AlertDialog.Builder(this);

尝试修改为:

AlertDialog.Builder builder = new AlertDialog.Builder(MyActivityName.this);

使用您的活动名称替换MyActivityName.

这修复了错误

原文链接:https://www.f2er.com/android/312238.html

猜你在找的Android相关文章