Search code examples
javaandroidrealmrealm-migration

IllegalStateException: It's not allowed to delete the file associated with an open Realm


i've an exception when i call Realm.deleteRealm(config):

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

I call this just after Realm.init() in Application.onCreate, so there is no reason to have others instances opened.

public void onCreate() {
    Realm.init(this);

    Realm realm;
    RealmConfiguration config = getConfig();
    try {
        realm = Realm.getInstance(config); // Will migrate if needed
    } 
    catch (RealmMigrationNeededException e) 
    {
        Realm.deleteRealm(config);
        realm = Realm.getInstance(config);
    }
}

I saw theses topics but can't see the solution:

https://github.com/realm/realm-java/issues/4552

https://github.com/realm/realm-java/issues/5416

Edit:

I think my problem is when i restart application to try fail migration. In application i have instances opened but not closed, and can't close them easily, code is too much complex. And when i restart application to test migration exception with adding field to models, maybe there are some instances opened from previous launch.

Edit 2:

I tried to come back to realm 3.0.0 (my previous release), and i have not this IllegalStateException. I'm currently using 4.2.0.

Maybe i miss something in changelog..


Solution

  • Before realm-java 4.1.0, Realm.deleteRealm() is not a process-safe call. It means it doesn't throw if there are Realm instances opened in other processes. But deleting while Realm instances opened will have a big chance to corrupt the DB file.

    From 4.1.0, Realm.deleteRealm() is a multi-process safe API. It will throw if it detects there are Realm instances opened on other processes/threads.

    So please check if you are using Realm in the other process and those are not closed properly before calling deleteRealm().