Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm: Iterating a RealmObject and clearing an ArrayList field

I have a RealmResults<Section> that has a RealmList<Event> field that I want to clear on each Section.

I've tried (insude mRealm.executeTransaction)

for (Section section : mSections) {
    section.getEvents().clear();
}

and

Iterator<Section> sectionIterator = mSections.iterator();
while (sectionIterator.hasNext()) {
    sectionIterator.next().getEvents().clear();
}

but Realm throws this exception

java.util.ConcurrentModificationException: No outside changes to a Realm is allowed while iterating a RealmResults. Use iterators methods instead.

like image 958
Ben Avatar asked Apr 27 '15 21:04

Ben


1 Answers

Since you are not actually removing elements that you are iterating over, you can just use a traditional for loop:

for (int i = 0; i < mSections.size(); i++) {
    mSections.get(i).getEvents().clear();
}

Note that if you did need to remove elements using an Iterator, you would need to use the remove() method on the Iterator itself.

See Documentation

like image 180
Daniel Nugent Avatar answered Sep 28 '22 06:09

Daniel Nugent