Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a realm instance has been closed already?

I'm using Realm for Android to store some data. When the user presses the log out button, I'd like to clear my entire Realm database. To do that, I have the following snippet of code:

realm.close();
realm.deleteRealmFile(this);
goToLoginActivity();

The issue now is in my onResume function. I'm getting the following exception:

Caused by: java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

My onResume code is as follows:

@Override
protected void onResume() {
    super.onResume();

    // I'm trying to check if the realm is closed; this does not work
    if (realm == null) {
        realm = Realm.getInstance(this);
    }

    // Do query using realm
}

How can I check to see if a realm object has been closed already? Alternatively, is there a better way to clear the database than deleting the realm file?

--

Edit: Just saw How can I easily delete all objects in a Realm for iOS. Any word on when the deleteAllObjects API will be available for Android? At the time of writing, Android is at version 0.80.0 and the API is available in iOS in 0.87.0.

like image 768
zongweil Avatar asked Apr 15 '15 21:04

zongweil


1 Answers

RealmObjects has a isValid() method which will return false if the object has been deleted in the database or the Realm is closed, eg.

Realm realm = Realm.getInstance(getContext());
Foo foo = realm.allObjects(Foo.class).findFirst();
if (foo.isValid()) {
  // Do something with Foo
} else {
  // Any operation will throw a IllegalStateException
}

Delete all

The android API has a Realm.clear(Class clazz) method that does the same thing. http://realm.io/docs/java/api/io/realm/Realm.html#clear-java.lang.Class- This is to mimic the rest of the Collection API's but I can see the confusion in regards to the iOS API.

like image 138
Christian Melchior Avatar answered Oct 11 '22 12:10

Christian Melchior