Skip to content

Instantly share code, notes, and snippets.

@krupalshah
Last active August 12, 2018 10:05
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 krupalshah/15fe8c732c6dce9a1773299c57eec474 to your computer and use it in GitHub Desktop.
Save krupalshah/15fe8c732c6dce9a1773299c57eec474 to your computer and use it in GitHub Desktop.
helper for shared prefs - java version - Refactoring step 2
public static <T> void setValue(Context context, String key, T value) {
if (value instanceof String) {
edit(context, (editor) -> editor.putString(key, (String) value));
} else if (value instanceof Boolean) {
edit(context, (editor) -> editor.putBoolean(key, (Boolean) value));
} else if (value instanceof Integer) {
edit(context, (editor) -> editor.putInt(key, (Integer) value));
} else if (value instanceof Float) {
edit(context, (editor) -> editor.putFloat(key, (Float) value));
} else {
throw new UnsupportedOperationException("Not yet implemented.");
}
}
public static <T> T getValue(Context context, String key, Class<?> aClass, T defaultValue) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
Object value;
if (aClass.equals(String.class)) {
value = sharedPreferences.getString(key, (String) defaultValue);
} else if (aClass.equals(Boolean.class)) {
value = sharedPreferences.getBoolean(key, (Boolean) defaultValue);
} else if (aClass.equals(Integer.class)) {
value = sharedPreferences.getInt(key, (Integer) defaultValue);
} else if (aClass.equals(Float.class)) {
value = sharedPreferences.getFloat(key, (Float) defaultValue);
} else {
throw new UnsupportedOperationException("Not yet implemented.");
}
return (T) value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment