Java Android:应用程序崩溃,出现BadTokenException错误(尝试显示AlertDialog)

Java Android:应用程序崩溃,出现BadTokenException错误(尝试显示AlertDialog),java,android,exception,android-alertdialog,Java,Android,Exception,Android Alertdialog,如果没有连接,我只想在屏幕上打印一个警报 以下是我在课堂上所做的扩展活动 if(isOnline()) { // do stuff.. } else { Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setMessage("No connection."); builder.setCancelable(true); AlertDialog dial

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

以下是我在课堂上所做的扩展活动

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:无法添加窗口标记-空标记不适用于应用程序

使用yourActivityName.this而不是getApplicationContext

使用yourActivityName.this而不是getApplicationContext

尝试使用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();
}
尝试使用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();
}
使用

而不是

 Builder builder =  new AlertDialog.Builder(getApplicationContext());
因为您需要传递当前活动上下文来显示AlertDialog,而不是应用程序上下文

而不是

 Builder builder =  new AlertDialog.Builder(getApplicationContext());
因为您需要传递当前活动上下文以显示AlertDialog,而不是应用程序上下文替换该行

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

因为您可能需要活动上下文而不是应用程序上下文

希望有帮助。

更换线路

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

因为您可能需要活动上下文而不是应用程序上下文

希望能有帮助