Proper way to clear Realm table/database?

chrystolin picture chrystolin · Oct 8, 2014 · Viewed 28.3k times · Source

I have a realm object with ~30 fields, after adding and removing several objects it seems that realm takes up quite a bit amount of space. The size of the allocated space seems to grow somewhat exponentially:

10*(add 100 + remove all) = 4 mb Data

15*(add 100 + remove all) = 33 mb Data

20*(add 100 + remove all) = 91 mb Data

25*(add 100 + remove all) = 179 mb Data

image

The file itself in data\data\app_folder\files\default.realm is 200 mb at this point.

Now this serious issue might be because i am not doing something properly. Before every insertion i do

Realm realm = Realm.getInstance(context);

realm.beginTransaction();
realm.where(RealmSubmission.class).findAll().clear();
// if i use realm.allObjects(RealmSubmission.class).clear(); the leak is even bigger, i get to 170mb Data with 20*(add 100 + remove all) even though both calls do the same by looking at their semantics.
realm.commitTransaction();

Adding items into realm looks like this:

    for (Submission submission : submissionList){
        realm.beginTransaction();

        RealmSubmission realmSubmission = realm.createObject(RealmSubmission.class);
        RealmObjectUtils.copySubmission(realmSubmission, submission);

        realm.commitTransaction();
    }

Any ideas?

Answer

Hugo Gresse picture Hugo Gresse · Jul 19, 2015

I've made a simple method to delete the realm database file when a migration exception occur (for dev). It also return a new realm instance to prevent any issue.

public Realm buildDatabase(){
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();

    try {
        return Realm.getInstance(realmConfiguration);
    } catch (RealmMigrationNeededException e){
        try {
            Realm.deleteRealm(realmConfiguration);
            //Realm file has been deleted.
            return Realm.getInstance(realmConfiguration);
        } catch (Exception ex){
            throw ex;
            //No Realm file to remove.
        }
    }
}