user1324936
user1324936

Reputation: 2187

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;
        }
    });
}

Upvotes: 3

Views: 1585

Answers (1)

Sabre
Sabre

Reputation: 4183

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.

Upvotes: 3

Related Questions