RealmObject AND Parcelable

I am new to Realm for Android, so I'm not sure if I am approaching this correctly. I have a class that looks like this:

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

The problem is that the Parcelable interface contains methods such as describeContents() writeToParcel() , and RealmObjects should not have methods other than getters and seters:

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

So my question is: how can I combine these two teams? Is there a better way than creating a separate class (maybe something like RealmEntry )? This will lead to a lot of duplicate code ...

+6
source share
3 answers

Now for this there is another way: just implement the RealmModel interface instead of the extension from RealmObject :

 @RealmClass public class User implements RealmModel { } 

Further information can be found in the Realm Documentation .

+4
source

UPDATE May 2016 . This answer is now deprecated if you are not already using Parceler. @Henrique de Sousa's solution is much better.


Actually, there is a workaround. You can get the desired result if you want to use a third-party library (Parceler) for the generation of Parcelable . See my answer to this other question 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 application will fail using org.parceler.ParcelerRuntimeException: Unable to create ParcelableFactory for io.realm.FeedRealmProxy .

+8
source

It is currently not possible to implement Parcelable in RealmObjects. One solution is to use two real files: by default - a storage of objects and specialized for temporary storage for rotation, etc.

0
source

Source: https://habr.com/ru/post/978945/


All Articles