Last active
August 29, 2015 14:08
-
-
Save mkuprionis/001ab54d476c194eb1c5 to your computer and use it in GitHub Desktop.
EnumPreference for Android following u2020 path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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