您的位置:首页 > Web前端

利用SharePreferences保存实体对象

2017-06-19 16:10 337 查看

1.使用场景

Android中SharePreferences只能存储基本数据类型,如果要对某一模块的数据模型作统一的暂存处理时,可以通过IO操作将对象实体转为String类型后保存在SharePreferences中

2.代码实现

public class LocalCacheUtil {
private static final String PREF_NAME_DEFAULT = "LocalModelCache";
/**
* 保存对象到本地SP中
* @param context
* @param t
* @param preferenceId
* @param <T>
*/
public static <T>void saveObj2SP(Context context, T t, String preferenceId) {
SharedPreferences preferences = context.getSharedPreferences(PREF_NAME_DEFAULT, Context.MODE_PRIVATE);
ByteArrayOutputStream bos;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(t);
byte[] bytes = bos.toByteArray();
String ObjStr = Base64.encodeToString(bytes, Base64.DEFAULT);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(preferenceId, ObjStr);
editor.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}

}

/**
* 从本地SP中读取对象
* @param context
* @param preferenceId
* @param <T>
* @return
*/
public static <T extends Object> T getObjFromSP(Context context, String preferenceId) {
SharedPreferences preferences = context.getSharedPreferences(PREF_NAME_DEFAULT, Context.MODE_PRIVATE);
byte[] bytes = Base64.decode(preferences.getString(preferenceId, ""), Base64.DEFAULT);
ByteArrayInputStream bis;
ObjectInputStream ois = null;
T obj = null;
try {
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bis);
obj = (T) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return obj;
}

/**
* 清楚暂存数据
* @param context
* @param preferenceId
*/
public static void clean(Context context,String preferenceId){
SharedPreferences preferences = context.getSharedPreferences(PREF_NAME_DEFAULT, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear().commit();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 存储 string