Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kenchoong/9c07792c0e9e4cb23524f945bb5ba092 to your computer and use it in GitHub Desktop.
Save kenchoong/9c07792c0e9e4cb23524f945bb5ba092 to your computer and use it in GitHub Desktop.
abstract class SharedPreferenceLiveData<T> extends LiveData<T> {
SharedPreferences sharedPrefs;
String key;
T defValue;
public SharedPreferenceLiveData(SharedPreferences prefs, String key, T defValue) {
this.sharedPrefs = prefs;
this.key = key;
this.defValue = defValue;
}
private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (SharedPreferenceLiveData.this.key.equals(key)) {
setValue(getValueFromPreferences(key, defValue));
}
}
};
abstract T getValueFromPreferences(String key, T defValue);
@Override
protected void onActive() {
super.onActive();
setValue(getValueFromPreferences(key, defValue));
sharedPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
@Override
protected void onInactive() {
sharedPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
super.onInactive();
}
}
public class SharedPreferenceBooleanLiveData extends SharedPreferenceLiveData<Boolean>{
public SharedPreferenceBooleanLiveData(SharedPreferences prefs, String key, Boolean defValue) {
super(prefs, key, defValue);
}
@Override
Boolean getValueFromPreferences(String key, Boolean defValue) {
return sharedPrefs.getBoolean(key, defValue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment