Implementing both Serializable and Parcelable interfaces from an object in Android - conflict
I have an object that I have to save to a file for reuse. The class of this object already implements Parcelable
for use in intents. My knowledge of the object is saved in the file suggests the implementation Serializable
, but when I do it, I get an error in the class that contains the object in the method of putExtra
intentions, because both Serializable
, and Parcelable
have this method.
Is there a way to avoid this, or just a way to save the state of the object and load it easily?
I have looked through several articles and I no longer know how I should save my object. thanks in advance
source to share
I believe that Parcelable
, and Serializable
both achieve the same goal in different ways and with different characteristics. Considering that if any class in your hierarchical object hierarchy implements an interface Parcelable
, you can override its method writeToParcel
, call super on it (so the members of superclasses will be bundled if implemented this way), and then, you should write your attributes to send, always keeping in mind that the order you use to store them is the order you will use to get the latter (FILO data structure)
EDIT
Just post your object where it complains and will report the conflict with the class you want to use as described here: fooobar.com/questions/181116 / ...
source to share
You have options other than Serializable
, but this may meet other requirements, such as avoiding library dependencies. You can write objects to a 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 that you probably don't have Bundles / Intents back and forth.
If you choose Serializable
, I would recommend structuring your objects so that they can be written to and read from Bundle
. Using the static MyObject.make(Bundle)
Bundle Instance Method and Method save()
keeps all constants and read / write in one place.
source to share