简体   繁体   English

在Android中保留Parcelable对象

[英]Persisting a Parcelable object in Android

I have a class in my Android app that I've made Parcelable so that it can be passed between Activities. 我在我的Android应用程序中有一个类,我已经制作了Parcelable,以便它可以在活动之间传递。

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. 似乎既然我已经实现了Parcelable,那么将它的输出传递给文件系统并稍后再读取是有意义的。

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? 或者,如果我想在活动之间传递对象并将其保存到文件系统,我必须同时实现Parcelable和Serialiazble吗?

From http://developer.android.com/reference/android/os/Parcel.html 来自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. 此类(以及用于将任意对象放入包中的相应Parcelable API)被设计为高性能IPC传输。 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. 因此,将任何Parcel数据放入持久存储中是不合适的:Parcel中任何数据的底层实现的更改都可能导致旧数据不可读。

For this problem, I did the following: 对于这个问题,我做了以下事情:

  1. Implemented Serializable in my object 在我的对象中实现了Serializable
  2. Added a toJSON() method to convert the object to a JSON object 添加了toJSON()方法以将对象转换为JSON对象
  3. Used a custom JSONSerializer to write the JSON objects to a file 使用自定义JSONSerializer将JSON对象写入文件
  4. Added a constructor that takes a JSON object as a parameter, used by the custom JSONSerializer 添加了一个构造函数,该构造函数将JSON对象作为参数,由自定义JSONSerializer使用

It ended up being pretty simple...I can paste some sample code if needed. 它最终非常简单......如果需要,我可以粘贴一些示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM