1

Whenever a user logs in, I am trying to check if the user is same as previously logged in user or not.If the user is different I am trying to delete all the database instance and then create the instance for the newly logged in user.If the user is same then user data should be deleted

How to delete database instance ? Tried

  Realm.getDefaultConfiguration()?.let {
            Realm.getDefaultInstance().close()
            Realm.deleteRealm(it)
          }

But got following exception

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: /data/data/com.mypackage.name/files/filename.realm

How to close all the instances and delete them?

Pradeep
  • 9,667
  • 13
  • 27
  • 34
Sravanthi
  • 11
  • 4
  • There is no general method to close all opened Realm instances, you need to manually keep track of each opened Realm and close it when you are done with it, as @VigneshK answered – Maelig Jan 22 '19 at 08:46

1 Answers1

1

If you have created equal number of realm instance, you need to close the realm instance equally.

Realm realm  = Realm.getDefaultInstance();
realm.beginTransaction();
.....//insert or update
realm.commitTransaction();
realm.close();

Or you can call Realm.deleteAll() in transaction block. This method call no need to close instance. But it will be cleared for all objects without DB schema.

Reference: How to Clear Database in Realm in Android

VigneshK
  • 753
  • 1
  • 10
  • 28