工具类代码
//将list集合转换成字符串
public static String SceneList2String(List SceneList) throws IOException {
// 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件。
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 然后将得到的字符数据装载到ObjectOutputStream
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
byteArrayOutputStream);
// writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以还原它
objectOutputStream.writeObject(SceneList);
// 最后,用Base64.encode将字节文件转换成Base64编码保存在String中
String SceneListString = new String(Base64.encode(
byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
// 关闭objectOutputStream
objectOutputStream.close();
return SceneListString;
}
//将字符串转换成list集合
@SuppressWarnings("unchecked")
public static List String2SceneList(String SceneListString)
throws StreamCorruptedException, IOException,
ClassNotFoundException {
byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
mobileBytes);
ObjectInputStream objectInputStream = new ObjectInputStream(
byteArrayInputStream);
List SceneList = (List) objectInputStream.readObject();
objectInputStream.close();
return SceneList;
}
真正调用的时候
//存储操作
SharedPreferences sp = Context.getSharedPreferences("mylist",Context.MODE_PRIVATE);
Editor edit = sp.edit();
try {
//将list集合转成字符串
String listStr = PhoneSaveUtil.SceneList2String(list);
//存储
edit.putString("mylistStr", listStr);
edit.commit();
} catch (IOException e) {
e.printStackTrace();
}
//取值操作
SharedPreferences sp = mContext.getSharedPreferences("mylist",Context.MODE_PRIVATE);
String liststr = sp.getString("mylistStr", "");
if (!TextUtils.isEmpty(liststr)) {
try {
list = PhoneSaveUtil.String2SceneList(liststr);
} catch (Exception e) {
e.printStackTrace();
}
}
转载于http://blog.sina.com.cn/s/blog_6ee426800102vobc.html 博主:石彧(谢谢您的资料让我在开发的路上进步)