Saving realm relationships does not persist them

纵饮孤独 提交于 2019-12-20 03:25:05

问题


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.


回答1:


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);
            }
        }
    }
});



回答2:


Are you using GSON? If so, did you follow the example as outlined in http://realm.io/docs/java/0.80.0/#gson?



来源:https://stackoverflow.com/questions/29355576/saving-realm-relationships-does-not-persist-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!