Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Preference with AlertDialog

My OnPreferenceClickListener creates a new AlertDialog like below. When I run the program I get the expection

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

What is wrong in my code?

public static class PrefsFragment extends PreferenceFragment {
    Preference pref= findPreference("text_preference1");
    pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            new AlertDialog.Builder(mContext).setTitle(R.string.alert_dialog_title)
                    .setMessage(R.string.alert_dialog_message)
                    .setPositiveButton(R.string.alert_dialog_ok,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setNegativeButton(R.string.alert_dialog_nein, null).show();

                    //do s.th.
        return false;
        }
    });
}
like image 230
user1324936 Avatar asked Mar 16 '26 05:03

user1324936


1 Answers

I think you're getting the ApplicationContext. But it shouldn't be used for creating Dialogs.

Instead of mContext in new AlertDialog.Builder(mContext) you should use getActivity(), which returns the activity associated with a fragment.

Since you are using fragments get the Activity's Context simply by calling the Fragments getActivity() method.

like image 123
Sabre Avatar answered Mar 17 '26 18:03

Sabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!