Android Realm, I want to code like this:
public void updateChecked(MyModel model) {
Realm.getDefaultInstance().beginTransaction();
model.setChecked(true);
Realm.getDefaultInstance().commitTransaction();
}
public void updateAllChecked() {
RealmResults<MyModel> results = Realm.getDefaultInstance().where(MyModel.class).findAll();
for (MyModel model : results) {
updateChecked(model);
}
}
with error when I call updateAllChecked():
java.util.ConcurrentModificationException: No outside changes to a Realm is allowed while iterating a RealmResults. Use iterators methods instead.
How to solve it?
You can't change objects during iteration. You need first manually copy all objects to another list and then iterate over them
List<MyModel> list = new ArrayList<>();
list.addAll(results);
realm.beginTransaction();
for (MyModel myModel : list){
myModel.setChecked(true);
}
realm.commitTransaction();