android – Why doesn't new AlertDialog.Builder(getApplicationContext()).create() work?

Question:

I've been seeing this problem for some time now, and I always have to keep an instance of the current Activity , rather than just an instance of the Context , and so far I haven't understood why, as the AlertDialog.Builder(Context context) , requires as an initialization parameter only an instance of the Context and not the Activity .

So if I do the following code:

AlertDialog alert = new AlertDialog.Builder(getApplicationContext()).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

The following running error is generated:

04-22 13:06:55.585: E/AndroidRuntime(3014): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appteste/com.example.appteste.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

If I pass the Activity as a parameter instead of the Context , everything works as expected:

AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();

Tested on the following Android versions: 4.0.3 and 4.4.2

My questions are as follows:

  1. Is this an Android bug?
  2. Am I doing something wrong?
  3. Why does it happen?

Note: For testing purposes, the codes presented were executed inside the onCreate(Bundle savedInstanceState) of the Activity .

Answer:

1 – Is this an Android bug?

Apparently not: getApplicationContext() should be used if you need a context whose lifecycle is separate from the current context , which is tied to the process lifetime rather than the current component. More details in the documentation.

2 – Am I doing something wrong?

Probably yes: So since you are using an Activity and creating your AlertDialog inside it, the context of that alert will be your activity. Based on this answer.

3 – Why does this happen?

The reasoning is that AlertDialog doesn't have a life outside of its Activity .

So it needs the context in which it was created, as getApplicationContext() is different from this of your activity you will get this Exception .

Scroll to Top