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;
}
});
}
I think you’re getting the
ApplicationContext. But it shouldn’t be used for creating Dialogs.Instead of
mContextinnew 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.