dariuus dariuus - 19 days ago 7
Android Question

How to obtain the value of the key passed to onSharedPreferenceChanged

In my PreferenceFragment I have implemented a OnSharedPreferenceChanged listener. It works. and I am able to see in the Log.i that the "key" matches the property that I am modifying (a switch preference).

But what I am unable to determine is how can I obtain the 'value' of the key? I have been struggling with this for about a day and a half and I know it has to be possible.

public class PrefsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// set all text correctly
onSharedPreferenceChanged(null, "");
}

@Override
public void onResume() {
super.onResume();
getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

Preference preference = findPreference(key);

Log.i("TAG", String.valueOf(key));
}


}

Answer

You need use sharedPreferences attribute to get the value of the key.

    public class PrefsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    // set all text correctly
    onSharedPreferenceChanged(null, "");
}

@Override
public void onResume() {
    super.onResume();
    getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
    getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    super.onPause();
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    String value = sharedPreferences.getString(key, "");

    Log.i("TAG", value);
}

}

The second parameter of getString() is a default value if the method does not find anything with that key (don't returns null)

You have to make sure that the type stored in the preferences corresponds with which you recover (String in this case). In other case you need use getInt(), or getFloat()...

Comments