How to display AlertDialog in a Fragment?

andro-girl picture andro-girl · Apr 18, 2012 · Viewed 96.5k times · Source

I want to display an alert dialog in my app. I am using fragments. I tried the below code to do this:

 AlertDialog ad = new AlertDialog.Builder(context)
            .create();
    ad.setCancelable(false);
    ad.setTitle(title);
    ad.setMessage(message);
    ad.setButton(context.getString(R.string.ok_text), new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
ad.show();

but it was crashing and the error in logcat was:

04-18 15:23:01.770: E/AndroidRuntime(9424): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

From internet I came to know that the crash is due to context issue. I had given context as

context = this.getActivity().getApplicationContext();

I don't know what is the problem with this. Can anybody help me?

Answer

Jave picture Jave · Apr 18, 2012

Replace context with getActivity().

The ApplicationContext should not be used for tasks such as creating Dialogs. As you are in a fragment you can instead get the Activity-Context simply by calling the Fragments getActivity() method.