Question

I know this might have discussed here before. But I am still confused what happens if I use getApplicationContext() to display a Dialog.

I have an application which uses getApplicationContext() to create AlertDialog.Builder, and the app crashes when the dialog is shown. But if I use SomeActivity.this context it works fine.

Note: This app was in play store for a while now and was working before, but not sure from which Android version this crashes.

Crash Stack Trace

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
        at android.view.ViewRootImpl.setView(ViewRootImpl.java:540)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
        at android.app.Dialog.show(Dialog.java:286)
        at android.app.AlertDialog$Builder.show(AlertDialog.java:951) 
Was it helpful?

Solution

But I am still confused what happens if I use getApplicationContext() to display a Dialog.

You blow up.

But if I use SomeActivity.this context it works fine.

Correct. A Dialog is owned by an Activity. You cannot use an Application, Service, or other Context to show a Dialog. Note, though, that you can use any Context to start a dialog-themed activity.

but not sure from which Android version this crashes

Android 1.0, as far as I know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top