Last active
August 29, 2015 14:21
-
-
Save dkozel/74af83b495d54a5c1012 to your computer and use it in GitHub Desktop.
EnumPreference
This file contains 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
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