您的位置:首页 > Web前端

SharedPreferences 存储实体类

2017-11-17 14:25 232 查看
首先SharedPreferences 存取的实体类不能太大,太大的还是建议存数据库。一般存取的实体类是用户喜好的封装类。

实现代码

/**
* 存放实体类以及任意类型
* @param context 上下文对象
* @param key
* @param obj
*/
public static void putBean(Context context, String key, Object obj) {
if (obj instanceof Serializable) {// obj必须实现Serializable接口,否则会出问题
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
String string64 = new String(Base64.encode(baos.toByteArray(),0));
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString(key, string64).commit();
} catch (IOException e) {
e.printStackTrace();
}

} else {
throw new IllegalArgumentException("the obj must implement Serializble");
}

}

public static Object getBean(Context context, String key) {
Object obj = null;
try {
String base64 = getSharedPreferences(context).getString(key, "");
if (base64.equals("")) {
return null;
}
byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return obj;}参考文章:http://blog.csdn.net/u014626094/article/details/47206263
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: