how to store java list in realm android database

↘锁芯ラ 提交于 2020-06-25 09:02:08

问题


How we can store java list in realm android database. I try to store it by using setter method present in my model, but it doesn't work and I get "Each element of 'value' must be a valid managed object" in exception message.

public void storeNewsList(String categoryId, List<News> newsList) { 
    Realm realm = Realm.getDefaultInstance(); 
    realm.beginTransaction(); 
    NewsList newsListObj = realm.createObject(NewsList.class); 
    newsListObj.setNewsList(new RealmList<>(newsList.toArray(new News[newsList.size()]))); 
    newsListObj.setCategoryId(categoryId); 
    realm.commitTransaction(); 
    realm.close(); 
} 

回答1:


Replace code with

public void storeNewsList(String categoryId, List<News> newsList) { 
    try(Realm realm = Realm.getDefaultInstance()) { 
        realm.executeTransaction(new Realm.Transaction() {
             @Override
             public void execute(Realm realm) {
                 NewsList newsListObj = new NewsList(); // <-- create unmanaged
                 RealmList<News> _newsList = new RealmList<>();
                 _newsList.addAll(newsList);
                 newsListObj.setNewsList(_newsList); 
                 newsListObj.setCategoryId(categoryId);
                 realm.insert(newsListObj); // <-- insert unmanaged to Realm
             }
        }); 
    }
} 



回答2:


In case if you're using @PrimaryKey then insertOrUpdate will do the trick

try(Realm realm = Realm.getDefaultInstance()) {
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                 RealmList<News> _newsList = new RealmList<>();
                                _newsList.addAll(myCustomArrayList);
                                realm.insertOrUpdate(_newsList); // <-- insert unmanaged to Realm

                            }
                        });
                    }


来源:https://stackoverflow.com/questions/43738163/how-to-store-java-list-in-realm-android-database

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