Search code examples
javaandroidarraylistpersistent

How to keep data stored in array after application has ended?


I'm working on an Android app and I got to a point where I need to add some Store objects to an ArrayList favoriteStores. The problem is that I want this list to persist after closing the application, because my list of favorite stores must stay there until I chose to delete particular items inside it. Anyone got any idea what type of implementation I might use? Thanks in advance,


Solution

  • If you don't want to save arraylist to database, you can save it to file. It is a great way if you just want to save arraylist and don't want to touch sqlite.

    You can save arraylist to file with this method

    public static <E> void SaveArrayListToSD(Context mContext, String filename, ArrayList<E> list){
            try {
    
                FileOutputStream fos = mContext.openFileOutput(filename + ".dat", mContext.MODE_PRIVATE);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(list);
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    And you can read that saved file to arraylist with this method

    public static Object ReadArrayListFromSD(Context mContext,String filename){
            try {
                FileInputStream fis = mContext.openFileInput(filename + ".dat");
                ObjectInputStream ois = new ObjectInputStream(fis);
                Object obj= (Object) ois.readObject();
                fis.close();
                return obj;
    
            } catch (Exception e) {
                e.printStackTrace();
                return new ArrayList<Object>();
            }
        }
    

    Hope this help.