3

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) 

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.