How to Clear Database in Realm in Android
Asked Answered
A

3

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.

Absentminded answered 6/6, 2016 at 0:20 Comment(0)
P
50

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.

Preteritive answered 6/6, 2016 at 2:43 Comment(5)
Do both methods also clear the data provided by RealmConfiguration#initialData()?Mincemeat
for latest version 4.3 you need to supply realm configuration as well e.g. Realm.deleteRealm(Realm.getDefaultConfiguration())Mattias
if we use realm cloud then it will delete all data from server as well?Grandeur
Is there a way to force-delete the database without making sure that all the Realm instances are closed?Lycurgus
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(); }); }Palstave
R
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

Rudie answered 13/4, 2017 at 6:45 Comment(0)
E
0

You can just update your realm schema version if you use deleteRealmIfMigrationNeeded

override fun onCreate() {
    super.onCreate()
    //add support for vector drawables on older APIs
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
    //init realm
    Realm.init(this)
    mApp = this

    //init set realm configs
    val realmConfiguration = RealmConfiguration.Builder()
        .schemaVersion(2) //if you used 1 before
        .allowQueriesOnUiThread(true)
        .allowWritesOnUiThread(true)
        .deleteRealmIfMigrationNeeded()// if migration needed then this methoud will remove the existing database and will create new database
        .build()
    Realm.setDefaultConfiguration(realmConfiguration)
Epigastrium answered 26/9, 2023 at 12:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.