I have a realm database that I use inside my app. The size of the file is 7mb. It has different objects inside. But then I call this function:
public static void deleteRealm(Context context) {
Realm realm = PSApplicationClass.getInstance().getRealm();
try {
Log.i("", "realm start");
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.delete(Destination.class);
realm.delete(TripStep.class);
realm.delete(TripStop.class);
realm.delete(Route.class);
realm.delete(RealmLocation.class);
realm.delete(CoordLocation.class);
realm.delete(PSTrip.class);
realm.delete(PSUser.class);
realm.delete(UserVehicle.class);
realm.delete(Vehicle.class);
realm.delete(MileageRates.class);
realm.delete(PSUserActivityMonth.class);
realm.delete(PSUserActivityWeek.class);
realm.delete(PSUserActivityYear.class);
realm.delete(Activity.class);
realm.delete(PSTripsStats.class);
realm.delete(Report.class);
realm.delete(Setting.class);
realm.delete(AddressComponent.class);
realm.delete(RealmString.class);
realm.delete(RealmInt.class);
realm.deleteAll();
}
});
Log.i("", "realm end");
} catch (Exception e) {
Log.i("", "realm continue initTrip error trying to add to realm:" + e.getMessage());
if (realm.isInTransaction()) {
realm.cancelTransaction();
}
}
}
And I check again. and the file has still 7 MB, but it is empty. no realm objects inside. Even more, if I get the same data again, it will grow to 14MB, so when I delete the data, it will have 14MB empty, and then grow to 21... and so on. Which causes it to become a huge file. And I'm pretty sure this should not happen. why does realm do this? This is the file that I'm talking about: https://www.dropbox.com/s/ri95yiwjutjiki6/myrealm.realm?dl=0
From Realm FAQ, this is to be expected, and database will reuse the space eventually.
That being said, you could force a database compaction by calling Realm#compactRealm(RealmConfiguration)
. See documentation.