Android – Custom Dialog Initialization Problem

Have you tried to add a Custom Dialog to your application? You followed the instructions from the official page and got an error about Window token null (android.view.WindowManager$BadTokenException)?

Following developer.android advice our code should look like this:

@Override
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog;
        switch(id) {
        case DIALOG_TEST:
        	Context mContext = getApplicationContext();
        	dialog = new Dialog(mContext);

        	dialog.setContentView(R.layout.custom_dialog);
        	dialog.setTitle("My custom Dialog");

        	TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
        	text.setText("Hello! I'm a custom dialog box! Nice to meet you!");
        	break;
        default:
            dialog = null;
        }
        return dialog;
    }

We have initialized our dialog by overriding the onCreateDialog() method from Activity class. When calling showDialog(DIALOG_TEST) the application crashes.

The problem is with the mContext object (obtained with getApplicationContext()) used for initializing our dialog. Not to go into many details about why and what, here’s a simple solution: as you are in an Activity object and this inherits Context you can just use this object as the Context for your dialog. So, just replace mContext with this (or <ActivityName>.this) whenever you need the current Context, and everything will work just fine.

New code:

@Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog;
        switch(id) {
        case DIALOG_TEST:
            // deleted - Context mContext = getApplicationContext();
            // deleted - dialog = new Dialog(mContext);
            dialog = new Dialog(this); // added
       	    dialog.setContentView(R.layout.custom_dialog);
            dialog.setTitle("My custom Dialog");

            TextView text = (TextView) dialog.findViewById(R.id.dialog_text);
            text.setText("Hello! I'm a custom dialog box! Nice to meet you!");
            break;
        default:
            dialog = null;
        }
        return dialog;
    }

The same solution can be applied to another example on the same developer.android page that uses AlertDialog and LayoutInflater and the dialog will be correctly displayed.

I hope this helped.

4 comments

  1. wow, you saved my day. I followed other tutorial, and it crashed.thank you very much.

  2. thank you..really helpful

  3. Yes!Official tutorial sucks

Leave a Reply

You must be logged in to post a comment.