1

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,

Răzvan Barbu
  • 189
  • 4
  • 16

3 Answers3

4

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.

Hein
  • 2,675
  • 22
  • 32
2

You can either use a database like SQLite (howto here) or use some serialization technique. There is a related question to serialization here.

General information about storing data in Android can be found here.

Community
  • 1
  • 1
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

Here's a nice post about data storage options in Android, read it carefully and select the option that you find the most appropriate.

Egor
  • 39,695
  • 10
  • 113
  • 130