Skip to content

Instantly share code, notes, and snippets.

@mkuprionis
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkuprionis/001ab54d476c194eb1c5 to your computer and use it in GitHub Desktop.
Save mkuprionis/001ab54d476c194eb1c5 to your computer and use it in GitHub Desktop.
EnumPreference for Android following u2020 path
public class EnumPreference<E extends Enum<E>> {
private final SharedPreferences preferences;
private final Class<E> clazz;
private final String key;
private final E defaultValue;
public EnumPreference(SharedPreferences preferences, Class<E> clazz, String key) {
this(preferences, clazz, key, null);
}
public EnumPreference(SharedPreferences preferences, Class<E> clazz, String key, E defaultValue) {
this.preferences = preferences;
this.clazz = clazz;
this.key = key;
this.defaultValue = defaultValue;
}
public E get() {
return E.valueOf(clazz, preferences.getString(key, defaultValue.name()));
}
public boolean isSet() {
return preferences.contains(key);
}
public void set(E value) {
preferences.edit().putString(key, value.name()).apply();
}
public void delete() {
preferences.edit().remove(key).apply();
}
}
@Module final class Module {
@Provides @Singleton EnumPreference<Gender> provideGenderPreference(SharedPreferences prefs) {
return new EnumPreference(prefs, Gender.class, "gender", Gender.WOMEN);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment