I have been observing this problem for some time, and I always have to keep an instance of Activity
current, instead of just keeping an instance of Context
, and until then I did not understand why, since the method AlertDialog.Builder(Context context)
, requires as an initialization parameter only one instance of Context
and not 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 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 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 the following versions of Android: 4.0.3 and 4.4.2
My doubts are as follows:
Note: For test purposes, the codes presented were executed within the
onCreate(Bundle savedInstanceState)
method ofActivity
.