利用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(); } }
相关文章推荐
- 利用tomcat-redis-session-manager做session同步时自定义类对象属性保存不上的解决方法
- 《Entity Framework 6 Recipes》中文翻译系列 (41) ------ 第七章 使用对象服务之标识关系中使用依赖实体与异步查询保存
- Entity Framework 实体框架的形成之旅--利用Unity对象依赖注入优化实体框架(2)
- 将一个业务实体对象序列化并保存到站点的指定目录下
- 利用serializable将对象保存到本地
- 利用NSKeyedUnarchiver对象归档方式保存数据
- 在利用SSH开发项目中保存带外键的对象
- 把对象的属性绑定到datalist中,建一个实体类,利用泛型,产生实体对象数组,把实体对象数组赋给datalist.DataSource...................
- (三)JAVA利用反射机制将XML中的内容放入实体对象中
- IOS通过NSCoding保存实体对象
- C# 利用系统剪贴板 保存 自定义对象
- 利用对象序列化将购物车保存在Cookie中
- IOS通过NSCoding保存实体对象
- 不创建实体对象,利用newstonjson得到json格式字符串,键对应的值
- golang利用gob序列化struct对象保存到本地
- 利用对象序列化将购物车保存在Cookie中
- 利用HttpWebRequest实现实体对象的上传
- Entity Framework 实体框架的形成之旅--利用Unity对象依赖注入优化实体框架(2)
- 利用XStream实现实体对象和xml文件相互转换
- 利用对象序列化将购物车保存在Cookie中