SharedPreferences是我们经常用到的存储,将它封装到一个类中我们的开发会方便很多,可以正常设置set get 方法,但是感觉代码有点多,今天看到一个老师的封装,刚好可以记录一下:
public class SPUtils {
private static SPUtils instance = new SPUtils();
private static SharedPreferences mSp;
//单例
private SPUtils(){
}
//得到单例
public static SPUtils getInstance(){
if(mSp == null){
mSp = Uiutils.getContext().getSharedPreferences("im", Context.MODE_PRIVATE);
}
return instance;
}
//保存
public void save(String key,Object value){
if(value instanceof String){
mSp.edit().putString(key, (String) value).commit();
}else if(value instanceof Boolean){
mSp.edit().putBoolean(key, (Boolean) value).commit();
}else if(value instanceof Integer){
mSp.edit().putInt(key, (Integer) value).commit();
}
}
//获取String类型数据
public String getString(String key,String defValue){
return mSp.getString(key,defValue);
}
//获取Boolean类型数据
public Boolean getBoolean(String key,boolean defValue){
return mSp.getBoolean(key,defValue);
}//获取Int类型数据
public int getInt(String key,int defValue){
return mSp.getInt(key,defValue);
}
}