使用Parceler库序列化领域对象

时间:2016-11-16 08:40:20

标签: android realm parcelable parcel

我在项目中使用Parceler库进行序列化。

我有一个像这样的RealmObject类:

@Parcel(implementations = {ARealmProxy.class}, value = Parcel.Serialization.BEAN, analyze = {A.class})
class A extends RealmObject {

    public int id;
    public int title;
}

我序列化一个A对象并将其放入Intent中:

Intent intent = new Intent(context, Main);
Bundle bundle = new Bundle();
A a = new A();
a.id = 10;
a.title = "title";
bundle.putParcelable("mykey", Parcels.wrap(a))
intent.putExtras(bundle);
context.startActivity(intent);

我反复将其反序列化:

Bundle bundle = getIntent().getExtras();
A a = Parcels.unwrap(bundle.getParcelable("mykey"));
// a's properties are null

并且其属性为null。 我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要使用getter / setter。

@Parcel(implementations = {ARealmProxy.class}, 
        value = Parcel.Serialization.BEAN, 
        analyze = {A.class})
class A extends RealmObject {
    @PrimaryKey 
    private int id;

    private int title;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public int getTitle() { return title; }
    public void setTitle(int title) { this.title = title; }
}

虽然从技术上讲,你不应该从RealmObject创建Parcelable对象。您应该通过intent bundle发送主键,并在另一个活动中重新查询该对象。

Intent intent = new Intent(context, Main.class);
Bundle bundle = new Bundle();
bundle.putLong("id", 10);

Bundle bundle = getIntent().getExtras();
A a = realm.where(A.class).equalTo(AFields.ID, bundle.getLong("id")).findFirst();