Skip to content

Instantly share code, notes, and snippets.

@lenamuit
Last active December 7, 2019 07:55
Show Gist options
  • Save lenamuit/9e9c2903913f4a433fc4 to your computer and use it in GitHub Desktop.
Save lenamuit/9e9c2903913f4a433fc4 to your computer and use it in GitHub Desktop.
SharePreferenceUtils for Android - the utils class to help you working with SharePreference
public class SharePrefUtils {
public enum Key{
//list of your keys here
}
private static SharedPreferences getSharePreference(Context context){
return context.getSharedPreferences("your_pref",Context.MODE_PRIVATE);
}
private static SharedPreferences.Editor getEditor(Context context){
SharedPreferences sharedPreferences = getSharePreference(context);
return sharedPreferences.edit();
}
/**
* check key exist or not
*/
public static boolean contain(Context context,Key key) {
return getSharePreference(context).contains(key.name());
}
/**
* Clear all
*/
public static void clear(Context context,Key key) {
getSharePreference(context).edit().remove(key.name()).commit();
}
public static String getString(Context context, Key key) {
return getSharePreference(context).getString(key.name(),null);
}
public static void saveString(Context context, Key key, String value){
getEditor(context).putString(key.name(),value).commit();
}
public static void saveLong(Context context, Key key, long value) {
getEditor(context).putLong(key.name(),value).commit();
}
public static long getLong(Context context, Key key){
return getSharePreference(context).getLong(key.name(),0);
}
//Save json object
public static void saveObject(Context context, Key key, Object obj){
Gson gson = new Gson();
String json = gson.toJson(obj);
getEditor(context).putString(key.name(), json).commit();
}
public static <T> T getObject(Context context, Key key, Class<T> clazz){
Gson gson = new Gson();
String json = getSharePreference(context).getString(key.name(), "");
return gson.fromJson(json, clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment