androidpreferenceactivityandroid-sharedpreferences

Check and update preference value in PreferenceActivity


Greetings my fellow developers, i am working on an android project in there is a need to store the user name in shared preferences. and do a bit of validation when user tries to update his/her name in the app settings, i am using EditTextPreference for this preference, and i am implementing onPreferenceChangeListner to get updated value and do some validation on the updated value here is my listner

@Override
public boolean onPreferenceChange(Preference preference, Object object) {
    String value = object.toString().trim();
    preference.setSummary(value);
    if (value.isEmpty()) { // this block works as expected
        preference.getEditor().clear().apply();
        Log.i("pref_old", preference.getExtras().getString("key", "-- old value cleared --")); // this always shows old value cleared - as expected
        return false;
    }


    preference.getEditor().putString("key", value).apply(); // this doesn't seems to be updating the value
    Log.i("pref_new", preference.getExtras().getString("key", "-- new value not created --")); // this always show "new value not created", but it should show updated value
    return true;
}

in this listner what i am trying to accomplish is to trim what user has entered, after that if string becomes empty remove the preference values so and update preferences if not then update trimmed value in the preferences, but problem is that after user enters the values, after trimming it value is not updated in shared preference. (in second part of the function)


Solution

  • it would seem that we need to always return false, if we are changing preference value in onPreferencechange and update preference value manually i still dont understand why after comiting values in preference when i try to log the new value it wont show me updated value, but in other activity where the same value is being called i can go there and confirm that either value has changed or not but solution to my problem was always return false and update preference value manually.