Android – unable to listen to preference changes?
class Userviewmodel extends viewmodel{
appPrefs.registerOnSharedPreferencechangelistener(preferencechangelistener)
}}
private SharedPreferences.OnSharedPreferencechangelistener preferencechangelistener;
public void subscribe() {
preferencechangelistener = (sharedPreferences, key) -> {
}
};
appPrefs.registerOnSharedPreferencechangelistener(preferencechangelistener);
};
public void unsubscribe(){
appPrefs.unregisterOnSharedPreferencechangelistener(preferencechangelistener);
}
Subscribe() and unsubscribe() are called from fragment onattach() and ondetach() methods, but they do not work when the property state changes. As you can see, preferencechangelistener is a class member rather than a method property. The value of preference is changed in another fragment. When I navigate to another fragment and return that preferencechangelistener is null, it is in onattach() I see the reason, but I don't know how to overcome it
resolvent:
I suggest registering onsharedpreferencechangelistener() during fragment onresume() and unregisteronsharedpreferencechangelistener() at onpause(). Also check the content of the preference name. This may be a typo
`
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Preference connectionPref = findPreference(key);
// Set summary to be the user-description for the selected value
connectionPref.setSummary(sharedPreferences.getString(key, ""));
}
}
`Official documents can be found here: https://developer.android.com/guide/topics/ui/settings.html#Fragment