Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display AlertDialog in a Fragment?

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?

like image 786
andro-girl Avatar asked Apr 18 '12 10:04

andro-girl


People also ask

How do you show DialogFragment?

Showing the DialogFragment It is not necessary to manually create a FragmentTransaction to display your DialogFragment . Instead, use the show() method to display your dialog. You can pass a reference to a FragmentManager and a String to use as a FragmentTransaction tag.

How do I use AlertDialog?

setMessage() is used for setting message to alert dialog. setIcon() is to set icon to alert dialog. The following code will create alert dialog with two button. setPositiveButton() is used to create a positive button in alert dialog and setNegativeButton() is used to invoke negative button to alert dialog.

Is AlertDialog deprecated?

A simple dialog containing an DatePicker . This class was deprecated in API level 26.


1 Answers

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.

like image 167
Jave Avatar answered Sep 20 '22 11:09

Jave