A. Steenbergen
A. Steenbergen

Reputation: 3440

What happened to removing items from realm.io? RealmException "Removing object is not supported."?

I am trying to delete the last Object from the Realm.io database based on a query, like so:

    Realm realm = Realm.getInstance(this);
    final RealmResults<RealmCustomLocation> databaseLocations = realm.where(RealmCustomLocation.class).findAllSorted("timeStamp", RealmResults.SORT_ORDER_DESCENDING);
    if(databaseLocations.size() >= 4){
        realm.beginTransaction();
        databaseLocations.removeLast();
        realm.commitTransaction();
    }

This is exactly like what is written at the Realm.io instructions about deletion:

realm.beginTransaction();
result.removeLast();
realm.commitTransaction()

But when I execute the code it always breaks with a RealmException

io.realm.exceptions.RealmException: Removing object is not supported.

Then I looked at the source code of RealmResults.java and I find this: enter image description here So no wonder it keeps crashing, removeLast() does nothing, only throw an error!

So my question is: How can I remove an object from the database then?!

I am using realm.io 0.77 (compile 'io.realm:realm-android:0.77.0') on Android.

I appreciate your help on this!

Upvotes: 10

Views: 6546

Answers (2)

kjoelbro
kjoelbro

Reputation: 6316

If you want to delete all objects, then I would create a while loop like this:

while (location.size() > 0) {
    location.removeLast();
}

Upvotes: 1

A. Steenbergen
A. Steenbergen

Reputation: 3440

I have contacted Realm.io support, awaiting an answer. For the meantime:

RealmCustomLocation location = databaseLocations.get(databaseLocations.size() - 1);
location.removeFromRealm();

works equivalent to

databaseLocations.removeLast()

so it can be used as a workaround.

Edit: Support told me that they are fixing it for future versions and recommended to use the workaround I posted for in the mean time.

Upvotes: 7

Related Questions