androidsharedpreferencesdialog-preference

Default value not setting with custom DialogPreference and bindPreferenceSummaryToValue


I made a custom DialogPreference to have a seekbar dialog in my settings, bound its summary to its value with bindPreferenceSummaryToValue method provided by default with a Setting Activity. (see the one below) Everything is working fine, however when the setting in first set, it is not set to default, but 0, because 0 is set as a fallback value in bindPreferenceSummaryToValue.

private static void bindPreferenceSummaryToValue(Preference preference) {
    preference.setOnPreferenceChangeListener(bindPreferenceSummaryToValueListener);
    if (preference instanceof SeekBarPreference) {
        bindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager.getDefaultSharedPreferences(preference.getContext()).
                        getInt(preference.getKey(), 0));  // Fallback value
    } else {
       ...

In my custom DialogPreference I have the following methods:

@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
    return a.getInt(index, 0);
}

@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
    progress= restorePersistedValue ? getPersistedInt(progress) : (int) defaultValue;
}

And of course in prefs.xml I have:

<SeekBarPreference
    android:defaultValue="10"
    android:key="my_key"
    ... />

And this in MainActivity:

PreferenceManager.setDefaultValues(this, R.xml.prefs, false);

Fallback value is used when value is null I guess, but why would it be null if I had it set to default?


Solution

  • Solved my issue with this:

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return a.getInt(index, 0);
    }
    
    @Override
    protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
        progress = restorePersistedValue ? getPersistedInt(progress) : (int) defaultValue;
        persistInt(progress);  // ADD THIS HERE
    }
    

    The reason is that when value is set from the xml preference file, it needs to be saved to the SharedPreferences by the preference itself. That's what persistInt does.