Reputation: 2873
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.
Upvotes: 19
Views: 4159
Reputation: 3673
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()
Upvotes: 3
Reputation: 81539
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.
Upvotes: 9
Reputation: 189
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();
Upvotes: 3
Reputation: 226
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.
Upvotes: 5