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

标签 android android-dialog runtimeexception android-windowmanager

我正在尝试打开一个对话窗口,但每次我尝试打开它时都会抛出此异常:

Uncaught handler: thread main exiting due to uncaught exception
android.view.WindowManager$BadTokenException: 
     Unable to add window -- token null is not for an application
  at android.view.ViewRoot.setView(ViewRoot.java:460)
  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
  at android.app.Dialog.show(Dialog.java:238)
  at android.app.Activity.showDialog(Activity.java:2413)

我通过使用显示器的 ID 调用 showDialog 来创建它。 onCreateDialog 处理程序记录良好,我可以毫无问题地逐步完成它,但我已经附加了它,因为我似乎遗漏了一些东西:

@Override
public Dialog onCreateDialog(int id)
{
    Dialog dialog;
    Context appContext = this.getApplicationContext();
    switch(id)
    {
        case RENAME_DIALOG_ID:
            Log.i("Edit", "Creating rename dialog...");
            dialog = new Dialog(appContext);
            dialog.setContentView(R.layout.rename);
            dialog.setTitle("Rename " + noteName);
            break;
        default:
            dialog = null;
            break;
    }
    return dialog;      
}

这有什么遗漏吗?一些问题谈到了在从 onCreate 创建对话框时遇到此问题,这是因为尚未创建 Activity ,但这是来自菜单对象的调用,并且 appContext 变量似乎已在调试器中正确填充。

最佳答案

而不是: 上下文 appContext = this.getApplicationContext(); 您应该使用指向您所在 Activity 的指针(可能是 this)。

我今天也被这个咬了,烦人的部分是 getApplicationContext() 逐字逐句来自 developer.android.com :(

关于安卓 1.6 : "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2634991/

相关文章:

Android - 闪烁 ImageView 进度对话框

c++ - 为什么 ideone.com 这样做?

java - RuntimeException - 由 : android. database.sqlite.SQLiteException 引起:没有这样的表:tbl(代码 1)

java - 如何处理现实项目中的运行时异常

android - 在 android 中使用 MQTT 的基本步骤

java - 无法验证从 Android 应用程序获取的 id token

javascript - 使用 JavaScript 在 Android 中显示软键盘

android - 即使在加载 View 后,我的 ProgressDialog 也不会关闭。

android - ListView 动画淡出然后添加新行