我们如何在realm android数据库中存储java列表。我尝试使用我的模型中存在的setter方法来存储它,但它不起作用,我在异常消息中得到“值'的每个元素'必须是一个有效的托管对象。
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();
}
答案 0 :(得分:9)
用
替换代码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
}
});
}
}
答案 1 :(得分:0)
如果你正在使用@PrimaryKey,那么insertOrUpdate
就可以解决这个问题
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
}
});
}