How to Clear Database in Realm in Android
Solution 1
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.
Solution 2
If you are sure there are not any other databases you want to save, you can delete all the other data also. you can follow this answer Clear Application's Data Programmatically
Related videos on Youtube
Nicks
Also known as nicks258, I am a Java enthusiast, making whatever GUI I can think of. I'm still learning and exploring Java. Some of my android apps include:Beacons, Funshoppers, NewsFeed, Event Creator(and much more). These are not extremely impressive, but they do keep me occupied, and they are fun to make. Flutter and Ionic Master (LOL). I hope you all love java, and thank you for reading my "About Me" I love this community, and I am most active here, but I also have accounts on Code Review and Meta Stack Exchange. Java is a great programming language, and I would definitely recommend it to a friend! ☕️
Updated on July 09, 2022Comments
-
Nicks almost 2 years
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.