Search code examples
javaandroidarraylistonresumeonpause

Android saving an ArrayList<CustomObject> onPause and onSaveInstanceState


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).

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?

Regards,

Marcus


Solution

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

    and to get back everything:

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