how to store java list in realm android database

前端 未结 2 2473
迷失自我
迷失自我 2021-02-20 18:20

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\' mu

相关标签:
2条回答
  • 2021-02-20 18:48

    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
    
                                }
                            });
                        }
    
    0 讨论(0)
  • 2021-02-20 18:49

    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
                 }
            }); 
        }
    } 
    
    0 讨论(0)
提交回复
热议问题