BadTokenException Error In Android Dialog
If you are creating a custom Dialog for Android, and following the Android Developers’ Creating Dialogs tutorial, then most likely you would have faced a Force Close with this exception showing up in logcat. I did too. Although I figured it out quickly, it might not be easy to find out for many, so posting it here for reference. Basically, the code given in the tutorial goes something like this:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
All looks well, but when you execute it, you will get a Force Close. The error appearing in logcat would be something like this:
Uncaught handler: thread main exiting due to uncaught exception
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
It isn’t apparent immediately that what is causing this error. The very first line in the code “Context mContext = getApplicationContext();” is the culprit.
Solution: Just replace “getApplicationContext()” with “this” (i.e. “Context mContext = this;” ) and it will work fine.
Explanation: As to why this is exactly an issue, I’m a bit fuzzy about it myself but this much I’m sure that the contexts that you get with getApplicationContext and this are different. On reading about this function from Android SDK help:
Return the context of the single, global Application object of the current process. This generally should only be used if you need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the current component.
I think this would mean is that getApplicationContext returns a context which is for the application itself and not the activity, while “this” would give you the context of the activity in which you are creating the dialog. I think since it is the activity which is associated with the UI (and for whom the window has been created), using the application context would have caused the crash here.