Reputation: 877
I have an object that i must save to file for reuse. The class of this object already implements Parcelable
for use in intents. My knowledge of saving an object to file says to implement Serializable
, but when i do, i get an error in the class that contains this object at the putExtra
method of an intent because both Serializable
and Parcelable
have this method.
Is there a way to avoid this, or just a way that i can save my object state and reload it easily?
I have looked at a few articles and i feel no more informed about how i should be saving my object. Thanks in advance
Upvotes: 5
Views: 5520
Reputation: 182
I don't know that you can implement both Serializable
and Parcelable
together but for convert a class from Serializable
to Parcelable
you can use this plugin:
Android Parcelable Code generator.
First remove implement Serializable then with ALT + Insert and click on Parcelable
you can generate your class.
Upvotes: 1
Reputation: 1
You have options other than Serializable
, but that may meet other requirements such as avoiding library dependencies. You can write objects to file using JSON or XML, which has the advantage of being readable. You may also need to consider versioning - what happens when you have files that need to be read by a class that contains a new field. Persistence brings with it some issues you probably don't have passing Bundles/Intents back and forth.
If you choose Serializable
I'd recommend structuring your objects so they can be written to and read from a Bundle
. Using a static MyObject.make(Bundle)
method and an instance Bundle save()
method keeps all the constants and read/write in a single location.
Upvotes: 0
Reputation: 4007
I believe that Parcelable
and Serializable
both reaches the same goal in different ways and with different performances. Given that, if some class in your object hierarchy alread implements the Parcelable
interface, you can override its writeToParcel
method, call the super for it (so the members of the super classes will be written to the parcel if they were implement that way) and then, you should write your attributes to the parcel, always keeping in mind that the order you use to save them is the order you will use to retrieve them latter (FILO data structure)
Just cast your object where it complains and tells about the conflict to the class you want to use as described here: https://stackoverflow.com/a/13880819/2068693
Upvotes: 4