I'm trying to open a dialog window, but every time I try to open it it throws this exception:
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)
I'm creating it by calling showDialog
with the display's id. The onCreateDialog
handler logs fine and I can step through it without an issue, but I've attached it since it seems like I'm missing something:
@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;
}
Is there something missing from this? Some questions have talked about having this problem when creating a dialog from onCreate
, which happens because the activity isn't created yet, but this is coming from a call from a menu object, and the appContext
variable seems like it is correctly populated in the debugger.
Instead of
getApplicationContext()
, just useActivityName.this
You can also do this
This worked for me !!
Just change it into
Instead of
As it's said, you need an Activity as context for the dialog, use "YourActivity.this" for a static context or check here for how to use a dynamic one in a safe mode
Android documents suggests to use getApplicationContext();
but it will not work instead of that use your current activity while instantiating AlertDialog.Builder or AlertDialog or Dialog...
Ex:
or
I had a similar issue where I had another class something like this:
Worked fine most of the time, but sometimes it crashed with the same error. Then I realise that in
MyActivity
I had...Because I was holding the object as
static
, a second run of the code was still holding the original version of the object, and thus was still referring to the originalActivity
, which no long existed.Silly stupid mistake, especially as I really didn't need to be holding the object as
static
in the first place...