问题
I have a class in my Android app that I've made Parcelable so that it can be passed between Activities.
I would like to be able to save this object to the filesystem. It seems that since I've already implemented Parcelable, it would make sense to pipe the output of this to the filesystem and read it back later.
Is there a correct way to do this? Or must I implement both Parcelable and Serialiazble if I want to both pass the object between Activities and also save it to the filesystem?
回答1:
From http://developer.android.com/reference/android/os/Parcel.html
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.
回答2:
For this problem, I did the following:
- Implemented Serializable in my object
- Added a toJSON() method to convert the object to a JSON object
- Used a custom JSONSerializer to write the JSON objects to a file
- Added a constructor that takes a JSON object as a parameter, used by the custom JSONSerializer
It ended up being pretty simple...I can paste some sample code if needed.
来源:https://stackoverflow.com/questions/7356035/persisting-a-parcelable-object-in-android