I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don’t need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can’t figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn’t the way to go about this? Is there a simpler method?
I have an ArrayList with custom objects. Each custom object contains a variety of
Share
After API 11 the
SharedPreferences EditoracceptsSets. You could convert your List into aHashSetor something similar and store it like that. When you read it back, convert it into anArrayList, sort it if needed and you’re good to go.You can also serialize your
ArrayListand then save/read it to/fromSharedPreferences. Below is the solution:EDIT:
Ok, below is the solution to save
ArrayListas a serialized object toSharedPreferencesand then read it from SharedPreferences.Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it’s simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.
In the
addTask()method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using theputString()method:Similarly we have to retrieve the list of tasks from the preference in the
onCreate()method:You can get the
ObjectSerializerclass from the Apache Pig project ObjectSerializer.java