|
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); |
|
} |
|
} |