I.S
I.S

Reputation: 2053

Could not 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 not working when the state of the property is changed. And as you can see preferenceChangeListener is class member not a method property. the value of preference is changed in another fragment, and when I'm navigating to another fragment and coming back preferenceChangeListener is null it initialized again in onAttach() ,I see the reason ,but I don't know how to overcome.

Upvotes: 4

Views: 354

Answers (1)

EugenUngurean
EugenUngurean

Reputation: 429

I recommend to registerOnSharedPreferenceChangeListener() during fragment onResume() and unregisterOnSharedPreferenceChangeListener() at onPause() . Also check the preference key name what is observed. It could be a typo there.

`

 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 documentation could be found here: https://developer.android.com/guide/topics/ui/settings.html#Fragment

Upvotes: 3

Related Questions