Search code examples
androidrealmrace-condition

Remove single Object from realm.io android if it still exists


I use realm to store items later shown in a ListView. The items have a delete button and if the user clicks that button two times, the app crashes, because realm says the object is no longer valid to operate on. Is there a more elegant solution than to just try and catch that exception and ignoring it?

Here is the code of the onClick method:

@Override
public void onClick(View view) {
    Toast.makeText(context, "Timer " + timer.getUUID() + " was stopped.", Toast.LENGTH_SHORT).show();
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();
    RealmResults<Timer> result = realm.where(Timer.class).equalTo("uuid", timer.getUUID()).findAll();
    result.deleteAllFromRealm();
    realm.commitTransaction();
}

Solution

  • I realized that since I already had a reference to that object, I could use realms isValid() method, see my code:

    @Override
    public void onClick(View view) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
            if (timer.isValid()) {
                Toast.makeText(context, "Timer " + timer.getUUID() + " was stopped.", Toast.LENGTH_SHORT).show();
                timer.deleteFromRealm();
            }
        realm.commitTransaction();
    }
    

    I also found the deleteFromRealm() Method on RealmObject, that I could not find earlier for some reason..
    So, the correct solution should be:

    RealmObject o = someRealmObject;
    realm.beginTransaction();
    if (o.isValid()) o.deleteFromRealm();
    realm.commitTransaction();