Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" Android 1.6: "android.view.WindowManager$BadTokenException: 无法添加窗口 - 令牌为空不适用于应用程序"
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application" Android 1.6: "android.view.WindowManager$BadTokenException: 无法添加窗口 - 令牌为空不适用于应用程序"
我正在尝试打开一个对话框窗口,但每次尝试打开它时都会抛出以下异常:\n
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)
\n我通过使用显示器的id调用showDialog
来创建它。 onCreateDialog
处理程序记录正常,我可以顺利地跟进它,但是我附上了它,因为似乎缺少了一些东西:\n
@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; }
\n这里有什么缺少的吗?有些问题讨论了在从onCreate
创建对话框时出现此问题,这是因为活动尚未创建,但这是从菜单对象的调用中出现的,而且调试器中的appContext
变量似乎被正确填充。
Android 1.6版本中出现了一个问题,即"android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"。这个问题的出现是由于在使用getApplicationContext方法时出现了错误。
根据Android官方文档的说明,我们应该使用getApplicationContext方法来获取应用程序的上下文。然而,实际上这种方法并不起作用,导致了上述的异常。因此,我们需要寻找一种解决方法。
解决这个问题的方法是,不使用getApplicationContext方法,而是直接使用当前Activity的实例来创建对话框。具体做法是,使用以下代码:
dialog = new Dialog(this);
其中,"this"通常是指启动对话框的Activity。
通过这种方式,我们可以避免使用getApplicationContext方法而导致的异常。
问题的原因是使用了错误的上下文(Context),解决方法是使用当前活动的上下文(Context)。
具体来说,问题出现在使用getApplicationContext()
方法获取上下文(Context)时。正确的做法是使用指向当前活动的指针,即this
。
这个问题是在开发者论坛上被报告的,用户从官方文档上复制了getApplicationContext()
的使用方法,但却导致了错误。这个问题也被报告为一个bug。
解决方法是使用myActivity.this
作为上下文(Context)来创建对话框。这个解决方法在一个回答中被提到,并且得到了许多用户的确认。
然而,这个问题在3年后仍然存在,并且仍然会导致应用程序崩溃。即使有人提出使用getApplicationContext()
的建议,但实际上应该使用活动的上下文(Context)来启动对话框。
总结一下,使用错误的上下文(Context)会导致android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
异常。解决方法是使用当前活动的上下文(Context),而不是其他上下文(Context)。这个问题已经被报告并被认定为一个bug,但仍然没有被修复。