Suppose the user can update the shared preferences from a popup dialog from MainActivity. In this case, I must listen to onSharedPreferenceChanged
event in order to apply the user's new settings. When I register the listener inside MyDialogFragment
's onCreateDialog()
method, the listener works correctly.
public class MyDialogFragment extends dialogFragment {
...
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sf, String key) {
Log.e("change", "pref changed");
}
};
SharedPreferences sp = getActivity().getsharedPreferences(myKey, Context.MODE_PRIVATE);
sp.registerOnSharedPreferenceChangeListener(listener);
}
However, if I register the same listener the same way from MainActivity
's onResume()
, the listener does not work when sharedpreferences are changed.
MainActivity
protected void onResume() {
super.onResume();
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sf, String key) {
Log.e("change", "pref changed");
}
};
SharedPreferences sp = this.getsharedPreferences(myKey, Context.MODE_PRIVATE);
sp.registerOnSharedPreferenceChangeListener(listener);
}
The only difference is that I replaced getActivity()
with this
when declaring sharedPreferences
in MainActivity's method. Is this expected that the above listener wouldn't work from MainActivity's scope?