androidsharedpreferences

Initial values for PreferenceScreen/PreferenceFragment when using PreferenceDataStore


I'm implementing a preference screen which is an XML file with the PreferenceScreen tag inflated in a PreferenceFragment. Typically this is backed by SharedPreferences, however for my particular situation we are swapping the SharedPreferences for a custom PreferenceDataStore for some of the preferences.

In the Fragment onCreate method we get the individual preferences and hook them to the PreferenceDataStore.

SwitchPreference pref = (SwitchPreference) findPreference("my_boolean_preference");
pref.setPreferenceDataStore(dataStore);

This works fine except that the current value is ignored when the screen is first displayed. How can I get the value when the screen is first displayed to be correct. Should I put the above code somewhere other than onCreate? Is there some refresh or rebind I should call?

Currently I'm working around the issue by manually setting the value right after calling setPreferenceDataStore.

pref.setChecked(dataStore.getBoolean("my_boolean_preference", false));

Solution

  • From here:

    Note: If you set a data store for a Preference after the Preference is attached to the hierarchy, the initial value for the Preference is not propagated again.

    You can do this:

    class MyFragment : PreferenceFragmentCompat() {
    
        override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) {
            super.onCreatePreferences(savedInstanceState, rootKey)
    
            // set dataStore before calling setPreferencesFromResource()
            preferenceManager?.preferenceDataStore = dataStore
    
            setPreferencesFromResource(R.xml.prefs_main, rootKey)
            ...
        }
    }