RealmObject AND Parcelable

半世苍凉 提交于 2020-01-21 04:34:07

问题


I'm new to Realm for Android so I'm not sure I'm approaching this the right way. I have a class which looks like this:

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

The problem is the Parcelable interface contains methods like describeContents() writeToParcel() and RealmObjects aren't supposed to have methods other than getters and setters:

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

So my question is: How can I make these two work together? Is there a better way than creating an separate class (maybe something like RealmEntry)? Doing so would result in a lot of duplicated code...


回答1:


Now there's a different workaround for that: just implement the RealmModel interface instead of extending from RealmObject:

@RealmClass
public class User implements RealmModel {

}

You can find more information in the Realm Documentation.




回答2:


UPDATE May 2016: This is answer is now out-dated unless you already use Parceler. @Henrique de Sousa's solution is much better.


Actually, there is a workaround. You can get the result you want if you're willing to use a third-party library (Parceler) for Parcelable generation. See my answer to this other question, quoted below for convenience.

With Parceler v0.2.16, you can do this:

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

Then, use Parcels.wrap(Feed.class, feed) instead of Parcels.wrap(feed) everywhere, otherwise your app will crash with org.parceler.ParcelerRuntimeException: Unable to create ParcelableFactory for io.realm.FeedRealmProxy.




回答3:


It's not possible at the moment to implement Parcelable on RealmObjects. One solution is to Use two realm files: the default one as your object store and a specialized one for temporary saves for rotations etc.




回答4:


Solution with 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() {
...


来源:https://stackoverflow.com/questions/27231259/realmobject-and-parcelable

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