24

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.

Nicks
  • 3,188
  • 3
  • 25
  • 29

2 Answers2

49

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.

beeender
  • 3,555
  • 19
  • 32
  • Do both methods also clear the data provided by `RealmConfiguration#initialData()`? – Jan Heinrich Reimer Mar 27 '17 at 22:47
  • 8
    for latest version 4.3 you need to supply realm configuration as well e.g. Realm.deleteRealm(Realm.getDefaultConfiguration()) – Shubham AgaRwal Jan 31 '18 at 05:33
  • if we use realm cloud then it will delete all data from server as well? – Rajesh N Jun 11 '18 at 16:38
  • Is there a way to force-delete the database without making sure that all the Realm instances are closed? – algrid Jan 02 '19 at 13:00
  • 1
    in rn (at least) you need to call it on your open realm instance within a write block like this: export async function deleteAll() { const realm = await Realm.open({ path: 'myrealm', schema: schema, }); realm.write(async () => { await realm.deleteAll(); }); } – Macilias Oct 15 '21 at 09:55
1

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

Community
  • 1
  • 1
erluxman
  • 18,155
  • 20
  • 92
  • 126