Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Clear Database in Realm in Android

Tags:

I want to clear whole database when a user press logout button and loads a new data when another user login.I tried many solutions like

try {         Realm.deleteRealm(realmConfiguration);        } catch (Exception ex){         throw ex;     } 

Also

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

But neither of the code works. Thanks in advance.

like image 226
Nicks Avatar asked Jun 06 '16 00:06

Nicks


People also ask

How do I delete data from a Realm database?

clear() method that . deleteAllFromRealm() is now the correct method to use.

Where is Realm database stored Android?

You can find your realm file in the Device File Explorer tab at the bottom right of Android Studio. The location will be /data/data/com.

How do you delete a Realm file?

To completely delete the Realm file from disk and start from scratch, it's simply a matter of using NSFileManager to manually delete it. For example, to delete the default Realm file: NSFileManager. defaultManager().


1 Answers

When you call Realm.deleteRealm(), you have to make sure all the Realm instances are closed, otherwise an exception will be thrown without deleting anything. By calling this method, all Realm files are deleted, which means all objects & schemas are gone. Catching all exceptions is a bad practise for any general cases.

Or you can call Realm.delelteAll() in a transaction block. This doesn't require all Realm instances closed. It will just delete all the objects in the Realm without clearing the schemas. And again, don't catch all exceptions.

like image 200
beeender Avatar answered Sep 25 '22 22:09

beeender