Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding standalone-objects to a RealmList

Is it possible to add standalone objects to a RealmList of an RealmObject already persisted in a realm?

Well, I know it doesnt work, because I get NPEs at (object.row.getIndex():RealmList:94)

What I want to do is:

mRealm.beginTransaction;
contact.getEmails().add(new Email());
mRealm.commitTransaction;

Because at that specific moment I dont have access to a Realm (well I could make it work, but I would have to rewrite some structures), for example:

//In Activity
Contact contact = Realm.where(Contact.class).equalsTo("name","pete").findAll().first();
mRealm.beginTransaction;
UpdateHelper.update(contact);
mRealm.commitTransaction;

//Helper class some else package
public static void update(Contact contact) {
    //do update stuff
    contact.getEmails().add(new Email());
}

`

like image 255
degill Avatar asked Jan 21 '15 15:01

degill


1 Answers

Christian from Realm here. No, currently that is not possible. It is an interesting use case though. The reason we have a Realm.copyToRealm() method is to make it really explicit that you should no longer use your old object. Allowing to add standalone objects to already persisted lists would make that less transparent. You also still need it to happen inside a write transaction. Adding a reference to the Realm in your method call would probably be the best way to solve it.

//In Activity
realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        Contact contact = realm.where(Contact.class)
                               .equalTo("name","pete")
                               .findFirst();
        if(contact != null) {
            UpdateHelper.update(contact, realm);
        }
    }
});

//helper method
public static void update(Contact contact, Realm realm) {
    //do update stuff
    Email email = realm.copyToRealm(new Email());
    contact.getEmails().add(email);
}
like image 117
Christian Melchior Avatar answered Oct 21 '22 10:10

Christian Melchior