Last active
August 12, 2018 10:05
-
-
Save krupalshah/15fe8c732c6dce9a1773299c57eec474 to your computer and use it in GitHub Desktop.
helper for shared prefs - java version - Refactoring step 2
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 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