I have an ArrayList
with custom objects that I would like to be able to save and restore on a screen rotate.
I know that this can be done with onSaveInstanceState
and onRestoreInstanceState
if I were to make the ArrayList
its own class, which implements either Parcelable
or Serializable
... But is there a way to do this without creating another class?
Yes, you can save your composite object in shared preferences. Let's say:
and now you can retrieve your object as:
You can use
onRetainNonConfigurationInstance()
. It allows you to save any object before an configuration change, and restore it after withgetLastNonConfigurationInstanceState
().Inside the activity:
Inside
onCreate()
:Handling Runtime Changes: http://developer.android.com/guide/topics/resources/runtime-changes.html Documentation: http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28%29
You do not need to create a new class to pass an ArrayList of your custom objects. You should simply implement the Parcelable class for your object and use Bundle#putParcelableArrayList() in
onSaveInstanceState()
andonRestoreInstanceState()
. This method will store an ArrayList of Parcelables by itself.Because the subject of Parcelables (and Serializables and Bundles) sometimes makes my head hurt, here is a basic example of an ArrayList containing custom Parcelable objects stored in a Bundle. (This is cut & paste runnable, no layout necessary.)
Implementing Parcelable
Save / Restore States