Skip to content

Instantly share code, notes, and snippets.

@dkozel
Last active August 29, 2015 14:21
Show Gist options
  • Save dkozel/74af83b495d54a5c1012 to your computer and use it in GitHub Desktop.
Save dkozel/74af83b495d54a5c1012 to your computer and use it in GitHub Desktop.
EnumPreference
package com.example.utils.prefs;
import android.content.SharedPreferences;
public final class EnumPreference<T extends Enum<T>> {
private final SharedPreferences preferences;
private final String key;
private final Class<T> type;
private final T defaultValue;
public EnumPreference(SharedPreferences preferences, String key, Class<T> type) {
this(preferences, key, type, null);
}
public EnumPreference(SharedPreferences preferences, String key, Class<T> type, T defaultValue) {
this.preferences = preferences;
this.key = key;
this.type = type;
this.defaultValue = defaultValue;
}
public boolean isSet() {
return preferences.contains(key);
}
public void set(Enum value) {
preferences.edit().putString(key, value.name()).apply();
}
public T get() {
String name = preferences.getString(key, null);
if (name != null) {
try {
return Enum.valueOf(type, name);
} catch (IllegalArgumentException ignored) {
}
}
return defaultValue;
}
public void delete() {
preferences.edit().remove(key).apply();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment