Persisting a Parcelable object in Android

扶醉桌前 提交于 2019-12-23 13:07:14

问题


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:

  1. Implemented Serializable in my object
  2. Added a toJSON() method to convert the object to a JSON object
  3. Used a custom JSONSerializer to write the JSON objects to a file
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!