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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With