Is there a simple way to delete old data from a Realm database? Like if some object has one day stored automatically delete it?
The alternative could be to add a field with the date and extract and compare it to decide if delete, but the question is if Realm has a method itself to achieve this.
The question is whether there is any other way to automatically remove old objects from Realm, such as a condition when we store data, a parameter, a configuration or a Realm method, and not just compare each time. It is obvious that with a query we can eliminate any object that we want.
I already saw some similar questions (like this one) about this, but none for Android (or Java), in the Realm docs the only similar approach I found is about migrations.
The specification of the linked question (not the answer), is just to clarify that this is not a Swift-based question and not mark it as duplicate at first glance.
Add a field with the date and query the ones you want to delete based on that
Then you can do
realm.where(MyClass.class)
.lowerThan("date", someDate)
.findAll()
.deleteAllFromRealm()
EDIT:
The question is whether there is any other way to automatically remove old objects from Realm, such as a condition when we store data, a parameter, a configuration or a Realm method, and not just compare each time.
No
It is obvious that with a query we can eliminate any object that we want.
The linked Swift-based answer does the exact same thing.
Set the alarm manager to every day (24 hr interval) On alarm manager callback just use the bellow code to delete older data
realm.where(BeanClass.class)
.lowerThan("date", currentDate)
.findAll()
.deleteAllFromRealm();
Nope, there is not such functionality in Realm itself.
Your alternative is good but I do not recommend to use background service for deleting data, so check/delete data when you query.
Yupp you can delete old realm data just like this,
realmConfiguration = new RealmConfiguration.Builder().build();
Realm.deleteRealm(realmConfiguration);
realm = Realm.getInstance(realmConfiguration);
In above lines, second line that is
Realm.deleteRealm(realmConfiguration);
perform deleting old realm data. Or you can delete data of specific class as,
realm.where(YourClass.class)
.lowerThan("date", currentDate)
.findAll()
.deleteAllFromRealm()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With