Dawid Hyzy
Dawid Hyzy

Reputation: 3761

How to send RealmObject in Bundle?

How to pass RealmObject through the Intents Bundle? Is there an way to write RealmObject to parcel? I don't want to use Serializable for know reasons.

Upvotes: 4

Views: 3231

Answers (3)

Renan Nery
Renan Nery

Reputation: 3765

You can't implement Parcelable in your Realm Model Classes, as mentioned in Realm Java Doc

Be aware that the getters and setters will be overridden by the generated proxy class used in the back by RealmObjects, so any custom logic you add to the getters & setters will not actually be executed.

But there is a work around that can fit for you, implementing Parceler Library you will be able to send objects across activities and fragments

Check out this closed issue on Realm Github https://github.com/johncarl81/parceler/issues/57

One of the answer show how to use Parceler with realm, it is necessary to set a custom params on @Parcel annotation.

Upvotes: 2

Dawid Hyzy
Dawid Hyzy

Reputation: 3761

The easiest solution is to use Parceler: https://realm.io/docs/java/latest/#parceler

For example:

// All classes that extend RealmObject will have a matching RealmProxy class created
// by the annotation processor. Parceler must be made aware of this class. Note that
// the class is not available until the project has been compiled at least once.
@Parcel(implementations = { PersonRealmProxy.class },
        value = Parcel.Serialization.BEAN,
        analyze = { Person.class })
public class Person extends RealmObject {
    // ...
}

Upvotes: 2

bladefury
bladefury

Reputation: 815

make your RealmObject implement Parcelable, here's a typical implementation from Developers' doc:

public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

Upvotes: -1

Related Questions