如何用android sharedpreferences保存List集合

在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();
}

进行保存获取。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值