Reputation: 189
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,
Upvotes: 1
Views: 4712
Reputation: 2683
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.
Upvotes: 4
Reputation: 40193
Here's a nice post about data storage options in Android, read it carefully and select the option that you find the most appropriate.
Upvotes: 0
Reputation: 30528
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.
Upvotes: 2