Search code examples
androidrealmrealm-list

Deleting RealmObject from RealmList


I have a RealmObject called, say A that is contained in a RealmList in RealmObjects B and C. B and C both have many to many relationships.

How do i remove the A from the RealmList in B but maintain it's relationship with C (i.e it should still be in Cs RealmList)?

In short, I need to know how to remove an object from a RealmList without affecting the other relationships the same object (without deleting it from Realm).


Solution

  • Just like any list, really.

    realm.executeTransaction(new Realm.Transaction() {
        B b = realm.where(B.class).equalTo(BFields.ID, bId).findFirst();
        Iterator<A> iterator = b.getRealmList().iterator();
        while(iterator.hasNext()) {
            A a = iterator.next();
            if(a.getId().equals(idToDelete)) {
                iterator.remove(); // removes from realm list, but not from Realm
                break;
            }
        }
    });
    

    But I think if you redefine hashCode() and equals() to work based on primary key, then that ought to work reliably with remove(Object object) as well.