Andreas Rudolph
Andreas Rudolph

Reputation: 1246

How can I delete all items in a RealmResults list fastest and easiest?

I have a line that returns a RealmResult with some sorted data.

I want to delete all these items the fastest and easiest. For example:

RealmResults<ElementEntry> currentElements = realm.where(ElementEntry.class).equalTo("type", 1).findAll();

//something like this then, would be preffered:
currentElements.removeFromRealm();

But I have to use iterators and what-not, but when I try that, I get this error:

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

So what CAN I use, if not the very iterator that is supposed to be used?

Upvotes: 1

Views: 5595

Answers (4)

axello
axello

Reputation: 545

Okay, I am using Realm 2.8.3 and have the following code:

    do {
        let realm = try Realm()
        try realm.write {
            var results = realm.objects(Category.self)
            results.removeAll()
            results.deleteAllFromRealm()
            results.clear()
        }
    } catch {}

All three methods are not defined on the Results<> datatype. What is the current answer for this question?

Upvotes: 0

David Miguel
David Miguel

Reputation: 14380

clear() is deprecated. You should use deleteAllFromRealm().

Delete the results of a query:

final RealmResults<Dog> results = realm.where(Dog.class).findAll();

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        // remove single match
        results.deleteFirstFromRealm();
        results.deleteLastFromRealm();

        // remove a single object
        Dog dog = results.get(5);
        dog.deleteFromRealm();

        // Delete all matches
        results.deleteAllFromRealm();
    }
});

Delete all objects from Realm database:

realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
        realm.deleteAll();
    }
});

Upvotes: 2

Georgi Koemdzhiev
Georgi Koemdzhiev

Reputation: 11931

To delate all objects in a realmResults do that:

RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.beginTransaction();
results.clear();
realm.commitTransaction()

To iterate you can do that:

realm.beginTransaction();
for (int i = 0; i < results.size(); i++) {
  results.get(i).setProperty("foo");
}
realm.commitTransaction();

Upvotes: 2

Fabian
Fabian

Reputation: 978

Try the clear method

From the docs:

Removes all objects from the list. This also deletes the objects from the  underlying Realm.
@throws IllegalStateException if the corresponding Realm is closed or in an incorrect thread.

https://github.com/realm/realm-java/blob/master/realm/realm-library/src/main/java/io/realm/RealmResults.java#L636

realm.beginTransaction();
currentElements.clear()
realm.commitTransaction();

Upvotes: 3

Related Questions