Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RealmObject AND Parcelable

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...

like image 693
frankelot Avatar asked Dec 01 '14 15:12

frankelot


People also ask

What is the use of Parcelable?

Parcelable and Bundle objects are intended to be used across process boundaries such as with IPC/Binder transactions, between activities with intents, and to store transient state across configuration changes.

How do you make Parcelable?

Create Parcelable class without plugin in Android Studioimplements Parcelable in your class and then put cursor on "implements Parcelable" and hit Alt+Enter and select Add Parcelable implementation (see image). that's it.


2 Answers

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.

like image 163
Vicky Chijwani Avatar answered Oct 09 '22 19:10

Vicky Chijwani


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.

like image 30
Henrique de Sousa Avatar answered Oct 09 '22 18:10

Henrique de Sousa