Harshal Bhatt
Harshal Bhatt

Reputation: 731

Android Realm default database clear

How to clear default realm database in android ? I tried following code but cannot resolve method deleteRealmFile.

Method 1 :

try {
   Realm.deleteRealmFile(context);
  //Realm file has been deleted.

} catch (Exception ex){
   ex.printStackTrace();
  //No Realm file to remove.
}

I tried to delete using configuration.

Method 2 :

try {
     Realm.deleteRealm(realm.getConfiguration());
     //Realm file has been deleted.
} catch (Exception ex){
     ex.printStackTrace();
     //No Realm file to remove.
}

but is gives the error:

java.lang.IllegalStateException: It's not allowed to delete the file associated with an open Realm. Remember to close() all the instances of the Realm before deleting its file.

Upvotes: 6

Views: 8645

Answers (2)

Vishwajit Palankar
Vishwajit Palankar

Reputation: 3083

Before Realm.deleteRealm(realm.getConfiguration()); just add realm.close() like below and it works like a charm

try {
      realm.close()
      Realm.deleteRealm(realm.getConfiguration());
                //Realm file has been deleted.
} catch (Exception ex){
                ex.printStackTrace();
                //No Realm file to remove.
}

Upvotes: 6

beeender
beeender

Reputation: 3565

As the exception described, you have to close all Realm instances which refer to the specific realm file.

This means, if you have called

Realm realm = Realm.getInstance(config);

You have to close the Realm before delete it.

realm.close();

And the Realm instances are based on reference counter, so please ensure every getInstance has a matched close.

This is very important, otherwise memory leak could happen. See https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances for some examples.

Upvotes: 2

Related Questions