android.view.WindowManager$BadTokenException: Unable to add window -- token null

今天在创建一个窗口的时候老是报错,很少郁闷。

引起错误的代码如下:

new AlertDialog.Builder(AppsInforAdapter.this.mContext) //出错的位置
                    .setTitle("提示")
                    .setMessage("确认删除该应用吗?")
                    .setCancelable(true)
                    .setNegativeButton("取消", new  DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .setPositiveButton("删除", new  DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            uninstallPkg(vh.info.activityInfo.packageName);
                        }
                    })
                    .show();
                    

 刚开始看起来是没有错误的。

但是log提示这个有错误,后来尝试了一下才知道是AppsInforAdapter.this.mContext的问题,但这个尝试是那里来的呢。

构造函数

public AppsInforAdapter(Context applicationContext, List<ResolveInfo> infos) {
        this.mContext = applicationContext;
        this.mInfos = infos;
    }

 

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        this.loadAPPInfo();
        
        gv_apps = (GridView) findViewById(R.id.apps); 
        gv_apps.setAdapter(new AppsInforAdapter(this.getApplicationContext(),this.infos));
//就是这里参数有问题
        
    }

 

正确的代码如下:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        this.loadAPPInfo();
        
        gv_apps = (GridView) findViewById(R.id.apps); 
        gv_apps.setAdapter(new AppsInforAdapter(this,this.infos)); //参数改变了
        
    }

所以不能一味的使用getApplicationContext()方法,要用activity。因为窗口的弹出要有activity。

猜你喜欢

转载自862123204-qq-com.iteye.com/blog/1894906