Reputation: 681
I know there are a few methods for saving data in an android application, but I'm wondering what is the simplest and/or most effective, or in other words which method would win-out on a scale of complexity/rationality/performance.
Basically I just have two Class ArrayLists (ArrayLists of class objects, not primitive data types). One ArrayList's object's constructor takes three integers,the other four. I basically need to store the value of those integers (I have methods for each set up to return the integers either as strings or ints) with a way of telling what each one belonged to.
For instance, if I have: arrayListOne.get(1).getNumbers() returning 1, 2, 3 arrayListTwo.get(1).getNumbers() returning 1, 2, 3, 4
and a whole heap of other indexes that would return different numbers, how can I store that data so when the app is closed and restarted it is reloaded and the values stay true to the indexes they were initialized at?
Upvotes: 0
Views: 822
Reputation: 51571
Writing it to internal storage is one solution. You can use the following as a static method inside a Util class:
Retrieve the ArrayList:
final static String OBJECT_1_LIST = "object_1_list";
static ArrayList<MyObject1> object1List = null;
static ArrayList<MyObject1> getObject1List(Context mContext) {
FileInputStream stream = null;
try {
stream = mContext.openFileInput(OBJECT_1_LIST);
ObjectInputStream din = new ObjectInputStream(stream);
object1List = (ArrayList<MyObject1>) din.readObject();
stream.getFD().sync();
stream.close();
din.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
if (object1List == null) {
object1List = new ArrayList<MyObject1>();
}
return object1List;
}
Similarly, to update the ArrayList:
private static void updateObject1List(Context mContext) {
FileOutputStream stream = null;
try {
stream = mContext.openFileOutput(OBJECT_1_LIST,
Context.MODE_PRIVATE);
ObjectOutputStream dout = new ObjectOutputStream(stream);
dout.writeObject(object1List);
stream.getFD().sync();
stream.close();
dout.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
To add an item:
static void addToObject1list(Context mContext, MyObject1 obj) {
Utilities.getObject1List(mContext).add(obj);
Utilities.updateObject1List(mContext);
}
Add methods for removing an item and clearing the ArrayList.
You also need MyObject1
to implement Serializable
:
public class MyObject1 implements Serializable {
....
....
}
Upvotes: 1
Reputation: 12527
I have found saving objects as JSON strings to be very simple and effective. Check out the GSON library. It will convert from JSON to java and java back to JSON with very little fiddling.
https://code.google.com/p/google-gson/
I love GSON for doing this very thing.
Upvotes: 0