简体   繁体   中英

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.

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.
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM