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?
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.
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.
A simple dialog containing an DatePicker . This class was deprecated in API level 26.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With