Issue
Oh boy, so I've spent the last hour or so reading and trying different ways of storing an ArrayList
of a Parcelable Object
in the Android preferences and Local Storage, and now I'm back to square one. I have downloaded and imported Gson, by the way, not that I could get it to work.
Basically, I have a class called Task
in an ArrayList<>
called taskList
that I need to save even when my users close my app. The Object
consists of a String
, some Ints
, some Booleans
and an ArrayList
of class Subtask
if that matters. What's important is that it seems I can't just write it as a list of Strings, and all the tutorials I've found only show saving simple ArrayLists like Strings and they have all been Serializable, not Parcelable.
EDIT: thanks for the suggestions, but I implement Parcelable to parcel specific objects in the list between activities..
Solution
According to Parcelable API,
Parcelable: Interface for classes whose instances can be written to and restored from a Parcel
.
And reading in Parcel API:
Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.
So if you want to store all the references of different types by an ArrayList
you must wrap all the objects to a common interface, in this case Serializable is your friend.
Also, according your question:
I need to save even when my users close my app.
If you check the android lifecycle, you will see you need to perform this action in onStop(), which is called when your activity is no longer visible to the user.
You can also refer to this answer for more information Shared preferences for creating one time activity
Answered By - Jordi Castilla
Answer Checked By - Marilyn (JavaFixing Volunteer)