2

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?

Rushi
  • 230
  • 1
  • 11
  • I believe using SharedPreference is the simpler method than any other. – Andro Selva May 16 '12 at 13:39
  • i think you should use database.see this shared pref only for promotives data types http://developer.android.com/guide/topics/data/data-storage.html#pref – Samir Mangroliya May 16 '12 at 13:43
  • yeah..thats true..but all objects are coming dynamically according the response from web service....so its too difficult for me to manage shared preferences for dynamically coming data....is it possible to save them at application level??? if yes then how??? – Rushi May 16 '12 at 13:44
  • It's either `SharedPreferences`,`SQLite` or a textile wether its raw text or formatted like XML/jSON or something. – Juan Cortés May 16 '12 at 13:50

2 Answers2

1

You can serialize the ArrayList using ObjectInputStream and ObjectOutputStream since all your object appear to be serializable.

Serialization is described here : http://java.sun.com/developer/technicalArticles/Programming/serialization/

In Android, the recommended place to save such files is to use the directory specified by Context.getCacheDir() so, on your Activity you simply call this.getCacheDir() to get it and then build a unique file name you feed to the ObjectStream objects.

Philippe Girolami
  • 1,876
  • 1
  • 13
  • 15
  • Serialization is not recommended on Android platform as it performs needless processes therefore it is slow. Parcelable is the successor of Serialization on Android – Gökhan Barış Aker May 16 '12 at 14:15
  • I agree, Parcelable would be more in line with the platform. It is however more complicated to do (see http://stackoverflow.com/questions/1626667/how-to-use-parcel-in-android) and, unless he's going to be doing hundreds of calls per second,I doubt anyone will see a difference in performance but I admit I've never checked this assumption. – Philippe Girolami May 16 '12 at 14:37
0

If you don't need it after the application is killed maybe you can try using onSaveInstanceState() and onRestoreInstanceState().

Here is a short example showing how to use it!

caiocpricci2
  • 7,714
  • 10
  • 56
  • 88