Spaceghost87
Spaceghost87

Reputation: 85

How to update a Child object in Realm Android

I'm using realm java in android, i have a parent class and a child class, here is my code, the problem is that every time this code is called, a new child object is created instead of update the Parent, so if I call this five times, i have 1 Parent and 5 Child objects, i just need 1 Parent and 1 Child, there is a way to achieve this

 class Parent extends RealmObject {
    @PrimaryKey
    private String someKey;
     Child child;
 }

 class Child extends RealmObject {
    private int someValue;
 }

 final Parent parent = realm.where(parent.class).equalTo("somekey", key)
        .findFirst();


    realm.executeTransaction(new Realm.Transaction() {
      @Override
      public void execute(Realm realm) {
        Child child = realm.createObject(Child
            .class);
        child.setSomeValue(value);

        parent.setChild(child);

      }
    });

Upvotes: 1

Views: 1894

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

I'm not entirely sure why you are creating a Child object each time you update the Parent, but if the idea is that the parent should always have a child, then you can do this:

realm.executeTransaction(new Realm.Transaction() {
  @Override
  public void execute(Realm realm) {
    if (parent.getChild() == null) { // Only create a child if it is missing.
      Child child = realm.createObject(Child.class);
      parent.setChild(child);
    }
    parent.getChild().setSomeValue(value);
    parent.setNotificationConstants(notificationConstants);
  }
});

Upvotes: 1

Related Questions