sharedPreference保存List集合实现

xiaoxiao2021-02-28  107

/** * 保存产品项目名称 */ public void setProctNameList(List<String> projectNames){ String listStr; try { listStr = SceneList2String(projectNames); editor.putString("productNameList", listStr); editor.commit(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public List<String> getProjectNameList(){ List<String> productNames = new ArrayList<String>(); String productName = mSharedPreferences.getString("productNameList", ""); try { productNames = String2SceneList(productName); } catch (StreamCorruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return productNames; }

主要实现方法:

//将List转化为String 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; } //将String转化成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;  }

转载请注明原文地址: https://www.6miu.com/read-50621.html

最新回复(0)