1

I have a problem creating a custom dialog. But I don't find the failure. Hopefully anybody can help me ...

protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    switch (id) {
    case DIALOG_ABOUT_ID:
        dialog = buildAboutDialog();
        break;
    default:
        dialog = null;
    }
    return dialog;
}

...

public Dialog buildAboutDialog() {
    Context mContext = getApplicationContext();
    Dialog dialog = new Dialog(mContext);

    dialog.setContentView(R.layout.about_dialog);
    dialog.setTitle("About this application");

    return dialog;
}

Results in the following error:

12-30 19:27:02.593: ERROR/AndroidRuntime(383): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

I checked if the returned dialog == null - but it isn't.

I also tried the second way (inflater) described at http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog

Mark
  • 7,507
  • 12
  • 52
  • 88

3 Answers3

3

I found out, that the dialog needs to be created with

Dialog dialog = new Dialog(this);

and not

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);

I don't exactly know why. Perhaps anybody can explain it to me?

Mark
  • 7,507
  • 12
  • 52
  • 88
  • 3
    Because the Dialog needs to be tied to the Activity not the Application. – rf43 Oct 13 '11 at 04:30
  • What if I want to show the dialog after a click on a button? "this" refers to the OnClickListener and not the Activity... – ffleandro Feb 13 '12 at 16:29
  • Unfortunately the the google code for this in creating a custom dialog has the getApplicationContext not this...http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog – JPM Mar 22 '12 at 21:13
1

Dialog dialog = new Dialog(contex); dialog.setContentView(R.layout.help_content);

this works for me .. may be getapplicationcontext not getting context of the your main class.

ud_an
  • 4,939
  • 4
  • 27
  • 43
0

As it turns out, Context of an activity is different then object returned by getApplicationContext(). This you can check by using logging, just output ActivityName.this and getApplicationContext.

The object returned by getApplicationContext is a global thing while context of an activity, well, belongs to that activity only.

Log.e(tag,""+ getApplicationContext());
Log.e(tag,""+CustomDialogActivity.this);

where CustomDialogActivity is my activity in which I want to show my dialog.

Dialogs require context of an activity and getApplicationContext() does not provide that. As written here (read comments) context of an activity is superset of getApplicationContext(). so It is a good thing to always pass context of an activity rather then the global context.

Also to answer ffleandro's comment of this page if you are inside onClick() you can use ActivityName.this to refer to activity. Hope this helps

Community
  • 1
  • 1