【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

posted @ 2013-12-10 13:10  风景线外  阅读(1025)  评论(0)    收藏  举报