Search code examples
androidsharedpreferencessummary

Android: Updating sharedPreferences Summary via listener


I am having a few issues with updating the summary line in the SharedPreferences as a preference changes. I have a registered OnSharePreferenceChangeListener in the onResume(), and an unregister of the same in the onPause().

The listener is functioning, and I am able to use the onSharedPreferenceChanges() method. The issue I am having is being able to retrieve the preference there so that I can call setSummary(). I am in Ice Cream Sandwich, and it appears as though the findPreference(key) method is deprecated. So:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);}

is not functioning, and actually returns null for pref. From the examples I have seen, you need to get a preference to call setSummary() on it, and ideas?


Solution

  • You shouldn't use an onSharedPreferenceChangedListener for this.

    Instead, use something similar to this.

    ListPreference myPreference = (ListPreference) findPreference("preference_key");
    myPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (((String)newValue).equals("some_value")) {
                preference.setSummary("my summary");
            }
        }
    });
    

    findPreference is not deprecated, but rather you shouldn't be using a PreferenceActivity (that is deprecated). If you only need to support Android 3.0+ then you should switch to PreferenceFragment's, the new method. If you need to support Android 2.1+ then it is fine and you can ignore the warnings.