3
I have been observing this problem for some time, and I always have to maintain an instance to Activity current, rather than maintaining only one instance to Context, and until then did not understand why, since the method AlertDialog.Builder(Context context), requires only one instance of Context and not of Activity.
So if I make the following code:
AlertDialog alert = new AlertDialog.Builder(getApplicationContext()).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();
The following error running 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
Already if I pass the Activity as a parameter instead of Context, everything works as expected:
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setTitle("Title");
alert.setMessage("Message");
alert.show();
I tested in the following versions of Android: 4.0.3 and 4.4.2
My doubts are as follows:
- This is a problem (Bug) of Android?
- I’m doing something wrong?
- Why does this happen?
Obs: For testing purposes, the codes presented were executed within the method
onCreate(Bundle savedInstanceState)ofActivity.
This is another of several that Android has. You’re not doing anything wrong, as long as you pass an Activity Context. This reminds me of that phrase from Ford: "You can choose any color for the car, as long as it’s black!"
– ramaral
@ramaral, so there’s nothing a programmer can do? Android is asking for a
Context, but actually he wants aActivity, is that what you meant right? And I’ll have to keep an instance of Activity where I intend to call aAlertDialog, without certain crying?– Fernando Leal
From the little research I’ve done, there’s nothing we can do. Activity is a Context such as Applicationcontext, but it seems that Alertdialog needs more than a simple Context, it needs something that Activity adds. Read this
– ramaral
@Ramaral, reading a little bit more, seems to me to be more confusing than at the beginning, because hell, they made a structure that way. I believe, that if this is an Android bug, it is a horrible Designer error, because it makes it difficult to understand a structure that could be much simpler, and a gap for bugs, because any inattentive developer (like me) can create a code that passes a
Context, and if it doesn’t get caught up in the tests, it might blow up in the end user. I don’t understand why this choice by the Android developers.– Fernando Leal