【问题标题】:Android : application crashes with BadTokenException Error (trying to show AlertDialog)Android:应用程序因 BadTokenException 错误而崩溃(试图显示 AlertDialog)
【发布时间】:2013-01-30 12:30:49
【问题描述】:

如果没有连接,我只想在屏幕上打印一个警报。

这是我在课堂上所做的扩展 Activity 的操作。

if(isOnline()) { 
    // do stuff..
} else {
    Builder builder =  new AlertDialog.Builder(getApplicationContext());
    builder.setMessage("No connection.");
    builder.setCancelable(true);
    AlertDialog dialog = builder.create();
    dialog.show();
}

然后我尝试使用 Debug 启动它,并收到以下错误:

android.view.WindowManager$BadTokenException: 无法添加窗口 -- 令牌 null 不适用于应用程序

【问题讨论】:

    标签: java android exception android-alertdialog


    【解决方案1】:

    使用

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

    而不是

     Builder builder =  new AlertDialog.Builder(getApplicationContext());
    

    因为您需要传递当前活动上下文来显示AlertDialog 而不是应用程序上下文

    【讨论】:

      【解决方案2】:

      换行

      Builder builder =  new AlertDialog.Builder(getApplicationContext());
      

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

      因为您可能需要 Activity Context 而不是 Application Context

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        尝试使用classname.this 以外的getApplicationContext() 这有时会导致问题

        if(isOnline()) { 
            // do stuff..
        } else {
            Builder builder =  new AlertDialog.Builder(getApplicationContext());
            builder.setMessage("No connection.");
            builder.setCancelable(true);
            AlertDialog dialog = builder.create();
            dialog.show();
        }
        

        【讨论】:

          【解决方案4】:

          使用yourActivityName.this 代替getApplicationContext()

          【讨论】:

            猜你喜欢
            • 2020-12-25
            • 2013-08-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-02-11
            • 1970-01-01
            相关资源
            最近更新 更多