如何用android sharedpreferences保存List集合

来源:互联网 发布:太阳能无网络监控器 编辑:程序博客网 时间:2024/04/28 22:49

在Android开发过程中有时需要用到一些简单的数据保存。

在系统自带的sharedpreferences中提供了一些列的数据类型,但有时候需要保存一个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;

}

 

 @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 mySharedPreferences= getSharedPreferences("scenelist", Context.MODE_PRIVATE);
Editor edit = mySharedPreferences.edit();
try {
    String liststr = Utils.SceneList2String(MyApp.scenesList);
    edit.putString(Constants.SCENE_LIST,liststr);
    edit.commit();
} catch (IOException e) {

    e.printStackTrace();
}

 

SharedPreferences sharedPreferences= getActivity().getSharedPreference ("scenelist", Context.MODE_PRIVATE);
String liststr = sharedPreferences.getString(Constants.SCENE_LIST, "");
try {
   showSceneList = Utils.String2SceneList(liststr);
} catch (StreamCorruptedException e) {
   e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
} catch (ClassNotFoundException e) {
   e.printStackTrace();
}

进行保存获取。

1 0
原创粉丝点击