【Android SharedPreference】 使用SharedPreferences存储复杂类型的数据

例如存储list,图片,对象。

通常做法,将这些数据进行转码,然后将转码后的数据以字符串的形式存储在sp的xml文件中。一般使用Base64转码。

以List为例:

 1 //将list转为字符串类型数据
 2 public static String list2String(List<E> list) throws IOException{
 3 //实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件
 4 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 5 //然后将得到的字符数据装载到ObjectOutputStream
 6 ObjectOutputStream oos = new ObjectOutputStream(baos);
 7 //writeObject 方法负责写入特定类的对象的状态,以便相应的readObject可以还原它
 8 oos.writeObject(list);
 9 //最后,用Base64.encode将字节文件转换成Base64编码,并以String形式保存
10 String listString = new String(Base64.encode(baos.toByteArray(),Base64.DEFAULT));
11 //关闭oos
12 oos.close();
13 return listString;
14 }

 

1 //将字符串形式保存的list还原
2 public static List<E> string2List(String str) throws StreamCorruptedException,IOException{
3 byte[] mByte = Base64.decode(str.getByte(),Base64.DEFAULT);
4 ByteArrayInputStream bais = new ByteArrayInputStream();
5 ObjectInputStream ois = new ObjectInputStream(bais);
6 List<E> stringList =(List<E>) ois.readObject();
7 return stringList;
8 }

 

文章参考:1.http://www.cnblogs.com/zyw-205520/archive/2013/04/09/3010912.html

     2.http://www.cnblogs.com/ikarl/archive/2012/11/13/2768344.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值