Matthias Loibl Matthias Loibl - 3 months ago 17
Android Question

Saving realm relationships does not persist them



I have a list of articles.

Those articles are inserted by using

realm.copyToRealmOrUpdate();
which works perfectly fine.

Now each article has an authorId which should not be persisted. Rather I want to find the stored author RealmObject and set its relationship for the article.

Author author = realm.where(Author.class).equalTo("id", article.getSerializedAuthor()).findFirst();
article.setAuthor(author);


Somehow this does not seem to be persisted by realm.

The same applies to the image RealmObject, just that I iterate before saving.

Here's the full snippet.

realm.beginTransaction();
realm.copyToRealmOrUpdate(articles.data);

for(Article article : articles.data) {
Author author = realm.where(Author.class).equalTo("id", article.getSerializedAuthor()).findFirst();
article.setAuthor(author);

for (Image image : article.getSerializedImages().data) {
if (article.getImages() == null) {
article.setImages(new RealmList<Image>());
}
article.getImages().add(image);
}
}
realm.commitTransaction();


Please let me know if you need more information.

Thanks.

Answer

Christian from Realm here. You keep manipulating the standalone objects you just copied to Realm, which won't work as they are still standalone objects and not "proper" Realm objects. You can read more here: http://realm.io/docs/java/0.80.0/#creating-objects and in the JavaDoc http://realm.io/docs/java/0.80.0/api/io/realm/Realm.html#copyToRealm-E-

So if you change you code to something like the below, it should work:

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        List<Article> realmArticles = realm.copyToRealmOrUpdate(articles.data);

        for(Article article : realmArticles) {
            Author author = realm.where(Author.class).equalTo("id", article.getSerializedAuthor()).findFirst();
            article.setAuthor(author);

            for (Image image : article.getSerializedImages().data) {
                article.getImages().add(image);
            }
        }
    }
});
Comments