4

如何通过 Intents Bundle 传递 RealmObject?有没有办法将 RealmObject 写入包裹?出于已知的原因,我不想使用 Serializable 。

4

3 回答 3

2

如Realm Java Doc中所述,您无法在 Realm 模型类中实现 Parcelable

请注意,getter 和 setter 将被 RealmObjects 在后面使用的生成代理类覆盖,因此您添加到 getter 和 setter 的任何自定义逻辑实际上都不会被执行。

但是有一个适合您的解决方法,实现Parceler 库,您将能够跨活动和片段发送对象

在 Realm Github 上查看这个已关闭的问题https://github.com/johncarl81/parceler/issues/57

答案之一显示了如何将 Parceler 与领域一起使用,有必要在 @Parcel 注释上设置自定义参数。

于 2015-07-28T14:52:22.073 回答
2

最简单的解决方案是使用 Parceler:https ://realm.io/docs/java/latest/#parceler

例如:

// All classes that extend RealmObject will have a matching RealmProxy class created
// by the annotation processor. Parceler must be made aware of this class. Note that
// the class is not available until the project has been compiled at least once.
@Parcel(implementations = { PersonRealmProxy.class },
        value = Parcel.Serialization.BEAN,
        analyze = { Person.class })
public class Person extends RealmObject {
    // ...
}
于 2016-06-19T11:18:30.287 回答
-1

使您的 RealmObject 实现,这是开发人员文档Parcelable中的典型实现:

public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }
于 2014-10-20T13:04:09.583 回答