atomontage
atomontage

Reputation: 105

Realm for Android: Store a non-RealmObject inside a RealmObject one

Straight to the code. We have two classes:

class Rocket extends RealmObject
{
 @PrimaryKey
 private long id;
 private String name;
 private Payload pl;
}

class Payload
{
 private String name;
 private double mass;
}

How do I store a Rocket in a Realm?

  1. I could manually serialize the Payload into a sort of String then save it along with the Rocket. But its slow.
  2. I could extend the Payload from RealmObject and save it into table. But if I do so I should delete the Payload every time I delete the parent Rocket. Its definitely not an option as the model gets really messy and complicated.

I may implement the Serializable or Parcelable interface if it requires me to but I really need to save my object into a Realm.

Thank you.

Upvotes: 2

Views: 683

Answers (1)

Adam S
Adam S

Reputation: 16394

It looks like your main concern with the obvious solution (extending RealmObject) is that you'd like to delete the Payload when you delete the parent Rocket. Unfortunately, cascading deletes are not yet supported. Your options are:

  • serialize to a string (note this has to be done outside of the Rocket object)
  • make Payload extend RealmObject and give it the same primary key as your Rocket objects and then delete them at the same time (via the same key)

I'd recommend the second solution, along with a method something like the following:

private void deleteRocket(long id) {
    realm.where(Rocket.class).equalTo("id", id).findFirst().removeFromRealm();
    realm.where(Payload.class).equalTo("id", id).findFirst().removeFromRealm();
}

Upvotes: 1

Related Questions