最近在项目中需要大量使用SharedPreferences,索性直接编写成帮助类,省事
简单介绍
- 保存SharedPreferences时直接使用
saveObject(Context context ,String name, String key, Object value)
这个方法,无论什么类型都可以保存,如果不够使用的话自己也可以添加 - 取出保存的数据按各自的类型来取
public class SharePreferenceUtils {
public static void saveObject(Context context ,String name, String key, Object value){
SharedPreferences sharedPreferences = context.getSharedPreferences(name, context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
// 以不同的类型来判断保存
if(value instanceof String){
edit.putString(key,(String) value);
}else if(value instanceof Long){
edit.putLong(key,(Long)value);
}else if(value instanceof Integer){
edit.putInt(key,(Integer) value);
}else if(value instanceof Boolean){
edit.putBoolean(key,(Boolean) value);
}
edit.commit();
}
// 提取String类型数据
public static String readString(Context context ,String name, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(name, context.MODE_PRIVATE);
String str = sharedPreferences.getString(key,"");
return str;
}
// 提取int类型数据
public static int readInt(Context context ,String name, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(name, context.MODE_PRIVATE);
int str = sharedPreferences.getInt(key,0);
return str;
}
// 提取long类型数据
public static long readLong(Context context ,String name, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(name, context.MODE_PRIVATE);
long str = sharedPreferences.getLong(key,0L);
return str;
}
// 提取boolean类型数据
public static boolean readBoolean(Context context ,String name, String key){
SharedPreferences sharedPreferences = context.getSharedPreferences(name, context.MODE_PRIVATE);
boolean str = sharedPreferences.getBoolean(key,false);
return str;
}
}
补充:
今天遇到一个新的任务,需要使用SharedPreferences保存bean对象,于是就添加了两个方法,存储及获取:
// 保存bean对象
public static void saveBeanByFastJson(Context context,String name,String key,Object obj){
SharedPreferences.Editor editor = (SharedPreferences.Editor) context.getSharedPreferences(name,Context.MODE_PRIVATE);
String toJson = new Gson().toJson(obj);
editor.putString(key,toJson).commit();
}
// 提取bean对象
public static <T> T getBeanByFastJson(Context context,String name,String key,Class<T> clazz){
String string = context.getSharedPreferences(name, Context.MODE_PRIVATE).getString(key, "");
return new Gson().fromJson(string,clazz);
}