Android的节约一个ArrayList< CustomObject>的onPause的onSaveInstanceState和 [英] Android saving an ArrayList<CustomObject> onPause and onSaveInstanceState

查看:150
本文介绍了Android的节约一个ArrayList< CustomObject>的onPause的onSaveInstanceState和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也充满了一些自定义的POJO的,我想,当用户切换屏幕方向(的onSaveInstanceState),当如坚持一个ArrayList用户点击后退按钮(的onPause)。

I have an ArrayList filled with some custom POJO's that I'd like to persist when the user switches screen orientation (onSaveInstanceState) and when e.g. the user hits the back button (onPause).

据我所知,共享preferences只能容纳原始数据类型和软件包不能坚持通用的ArrayList引用。

As far as I know, the SharedPreferences can only hold primitive data types and bundles can not hold references to generic ArrayLists.

如何解决这个任何提示?

Any tips on how to tackle this?

问候,

马库斯

推荐答案

1 - 创建一个类,并把要存储例如一切的ArrayList 你的<$ C的$ C> POJO ,并做出类实现序列化接口。

1- create a class and put everything you want to store for example arraylist of your POJO and make that class implement Serializable interface.

class MyBundle  implements Serializable {

   ArrayList<POJO> mPOJO;


   MyBundle( ArrayList<POJO> pojo){

    mPOJO= pojo;


   }

}

2 - 写入到文件:

2- write it to file:

 ObjectOutputStream oos = null;
 FileOutputStream fout = null;
 try{
        FileOutputStream fout = new FileOutputStream("Your file path");
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(mb); // mb is an instance of MyBundle
 } catch (Exception ex) {
        e.printStackTrace();
 }finally {
   if(oos  != null){
     oos.close();
   } 
 }

和找回的一切:

 ObjectInputStream objectinputstream = null;
 try {
        streamIn = new FileInputStream("Your file address");
        objectinputstream = new ObjectInputStream(streamIn);
        MyBundle mb = (MyBundle) objectinputstream.readObject();

   } catch (Exception e) {
        e.printStackTrace();
   }finally {
     if(objectinputstream != null){
        objectinputstream .close();
     } 
   }

这篇关于Android的节约一个ArrayList&LT; CustomObject&GT;的onPause的onSaveInstanceState和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆