zoukankan      html  css  js  c++  java
  • android AlertDialog显示错误 Unable to add window token null is not for an application解决办法

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            findViewById(R.id.button1).setOnClickListener(new Button.OnClickListener() {
                
                public void onClick(View v) {
                    new AlertDialog.Builder(getApplicationContext())
                    .setTitle(R.string.dialogTitle)
                    .setMessage(R.string.dialogMessage)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(getApplicationContext(), "你按了确定。", Toast.LENGTH_SHORT).show();
                        }
                    }).show();
                }
            });
        }


    报错:Unable to add window token null is not for an application

      

    异常原因:AlertDialog创建语句public AlertDialog.Builder (Context context)中,不能使用getApplicationContext()得到的context,而必须使用Activity,所以解决如下

    解决办法:

    将 new AlertDialog.Builder(getApplicationContext()) 改为 new AlertDialog.Builder(MainActivity.this)

    其中MainActivity 为当前Activity的名称 
  • 相关阅读:
    微擎 关注发送推荐消息
    修改 processor.php 文件,监听用户对该应用的消息
    微擎返回图文信息
    微擎客服消息发送的函数
    mui 底部导航栏的实现
    两张表的关联查询
    微擎 截取字符串
    webStorm中NodeJs 没有智能提示
    OpenCV 实现自己的线性滤波器
    OpenCV 基本的阈值操作
  • 原文地址:https://www.cnblogs.com/jxgxy/p/2652186.html
Copyright © 2011-2022 走看看