public class SharedPreferencesUtils {
/**
* 保存在手机里面的文件名
*/
private static final String FILE_NAME = "share_date";
/**
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
* @param context
* @param key
* @param object
*/
public static void setParam(Context context , String key, Object object){
String type = object.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
if("String".equals(type)){
editor.putString(key, (String)object);
}
else if("Integer".equals(type)){
editor.putInt(key, (Integer)object);
}
else if("Boolean".equals(type)){
editor.putBoolean(key, (Boolean)object);
}
else if("Float".equals(type)){
editor.putFloat(type, (Float)object);
}
else if("Long".equals(type)){
editor.putLong(type, (Long)object);
}
editor.commit();
}
/**
* 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
* @param context
* @param key
* @param defaultObject
* @return
*/
public static Object getParam(Context context , String key, Object defaultObject){
String type = defaultObject.getClass().getSimpleName();
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
if("String".equals(type)){
return sp.getString(key, (String)defaultObject);
}
else if("Integer".equals(type)){
return sp.getInt(key, (Integer)defaultObject);
}
else if("Boolean".equals(type)){
return sp.getBoolean(key, (Boolean)defaultObject);
}
else if("Float".equals(type)){
return sp.getFloat(type, (Float)defaultObject);
}
else if("Long".equals(type)){
return sp.getLong(type, (Long)defaultObject);
}
return null;
}
}
public class SpUtils {
private static SpUtils instance;
private SharedPreferences sp;
public SpUtils(){
sp = MyApplication.context.getSharedPreferences("mksh", Context.MODE_PRIVATE);
}
public static SpUtils getInstance(){
if(instance == null){
synchronized (SpUtils.class){
if(instance == null){
instance = new SpUtils();
}
}
}
return instance;
}
/**
* 设置数据
* @param key
* @param value
*/
public void setValue(String key, Object value){
SharedPreferences.Editor editor = sp.edit();
if(value instanceof String){
editor.putString(key, (String) value);
}else if(value instanceof Integer){
editor.putInt(key, (Integer) value);
}else if(value instanceof Boolean){
editor.putBoolean(key, (Boolean) value);
}else if(value instanceof Float){
editor.putFloat(key, (Float) value);
}else if(value instanceof Long){
editor.putLong(key, (Long) value);
}
editor.commit();
}
public String getString(String key){
return sp.getString(key,"");
}
public int getInt(String key){
return sp.getInt(key,0);
}
public Boolean getBoolean(String key){
return sp.getBoolean(key,false);
}
public float getFloat(String key){
return sp.getFloat(key,0);
}
public Long getLong(String key){
return sp.getLong(key,0);
}
/**
* 删除对应的key
* @param key
*/
public void remove(String key){
sp.edit().remove(key).commit();
}
}
网友评论