How to display AlertDialog in a Fragment?

JavaAndroidFragmentAndroid AlertdialogAndroid Context

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

More Information about this question (AlertDialog in a fragment, managed inside an event):

If you call AlertDialog within an event like onClick(View v) or onLongClick(View v) you can use

public boolean onClick(View v) {
    ...
    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(v.getContext());
    ...
}

Solution 3 - Java

Try to use DialogFragment, DialogFragment is better when you use Fragments

Solution 4 - Java

I have had similar issues whereby I was trying to create an AlertDialog from a Fragment. A NullPointerException arose from it. Initially I did as follows:

AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();

The NullPointerException occurred specifically when calling alertDialog.show() later on in the code. But after searching the documentation for AlertDialog.Builder(), there seemed to be another way to initialize it [AlertDialog.Builder Doc], which is to include a theme/resId as shown below:

AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.Theme_AppCompat_Dialog_Alert).create();

This resolved the NullPointerException at hand. Hope this helps you as well!

Solution 5 - Java

I used it in an adapter inside a listView, therefore I couldn't use getActivity(). In order to make it work I used getActivity() for the context in the instantiation of the adapter in the fragment:

this.adapter = new myAdapter(getActivity(), factory);

Later in the other class (the adapter's class) I was able to use getContext()and it worked.

Solution 6 - Java

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

Solution 7 - Java

                       AlertDialog alert= null;
						AlertDialog.Builder build= new AlertDialog.Builder(getActivity());
						build.setTitle("title");
						build.setItems(stringarrayname, new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
							//Toast.makeText(getActivity(), "hi", Toast.LENGTH_SHORT).show();	
								
							}
						});
						build.create().show();

Solution 8 - Java

You can try this or use DialogFragment

private void showAlert(final int position) {
        new AlertDialog.Builder(getActivity().getApplicationContext())
                .setTitle("Delete entry")
                .setMessage("Are you sure you want to delete this entry?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                      //  deleteSuggestions(position);
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

Solution 9 - Java

The solution is to replace by getActivity()

AlertDialog.Builder alert = new AlertDialog.Builder(getActivity(),R.style.MaDialog);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionandro-girlView Question on Stackoverflow
Solution 1 - JavaJaveView Answer on Stackoverflow
Solution 2 - JavaJDCoderView Answer on Stackoverflow
Solution 3 - JavaFUBUsView Answer on Stackoverflow
Solution 4 - JavaSyuqriView Answer on Stackoverflow
Solution 5 - JavaHanan NView Answer on Stackoverflow
Solution 6 - JavaG.ONEView Answer on Stackoverflow
Solution 7 - JavaudaysagarView Answer on Stackoverflow
Solution 8 - JavaRanjithkumarView Answer on Stackoverflow
Solution 9 - JavacimohamedView Answer on Stackoverflow