如何在领域 android 数据库中存储 java 列表
how to store java list in realm android database
我们如何在领域 android 数据库中存储 java 列表。我尝试使用模型中存在的 setter 方法来存储它,但它不起作用,我在异常消息中得到 "Each element of 'value' must be a valid managed object"。
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();
}
将代码替换为
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
}
});
}
}
如果您使用的是@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
}
});
}
我们如何在领域 android 数据库中存储 java 列表。我尝试使用模型中存在的 setter 方法来存储它,但它不起作用,我在异常消息中得到 "Each element of 'value' must be a valid managed object"。
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();
}
将代码替换为
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
}
});
}
}
如果您使用的是@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
}
});
}