RealmObject和Parcelable

问题描述 投票:8回答:4

我是Realm for Android的新手,所以我不确定我是以正确的方式接近这个。我有一个看起来像这样的课:

public class Entry extends RealmObject implements Parcelable {
    ...
}

问题是Parcelable接口包含像describeContents() writeToParcel()和RealmObjects这样的方法不应该有getter和setter以外的方法:

Error:(81, 17) error: Only getters and setters should be defined in model classes

所以我的问题是:我如何让这两个一起工作?有没有比创建一个单独的类(可能像RealmEntry)更好的方法?这样做会导致大量重复的代码......

java android sqlite parcelable realm
4个回答
4
投票

现在有一个不同的解决方法:只需实现RealmModel接口,而不是从RealmObject扩展:

@RealmClass
public class User implements RealmModel {

}

您可以在Realm Documentation找到更多信息。


9
投票

更新2016年5月:除非您已使用Parceler,否则现在的答案已过时。 @Henrique de Sousa的解决方案要好得多。


实际上,有一种解决方法。如果您愿意使用第三方库(Parceler)进行Parcelable生成,您可以获得所需的结果。有关方便,请参阅下面引用的my answer to this other question

使用Parceler v0.2.16,您可以这样做:

@RealmClass      // required if using JDK 1.6 (unrelated to Parceler issue)
@Parcel(value = Parcel.Serialization.BEAN, analyze = { Feed.class })
public class Feed extends RealmObject {
    // ...
}

然后,到处使用Parcels.wrap(Feed.class, feed)而不是Parcels.wrap(feed),否则你的应用程序将与org.parceler.ParcelerRuntimeException: Unable to create ParcelableFactory for io.realm.FeedRealmProxy崩溃。


0
投票

目前在RealmObjects上实现Parcelable是不可能的。一种解决方案是使用两个领域文件:默认文件作为对象库,一个专用文件用于临时保存轮换等。


0
投票

Kotlin解决方案:

import io.realm.com_labtest_di_model_EntryRealmProxy
import org.parceler.Parcel


@RealmClass
@Parcel(implementations = arrayOf(com_labtest_di_model_EntryRealmProxy::class),
    value = org.parceler.Parcel.Serialization.BEAN,
    analyze = arrayOf(Movie::class))
open class Entry() : RealmObject() {
...
© www.soinside.com 2019 - 2024. All rights reserved.