Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean up old Realm objects?

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.

I'm not looking for a query

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.

like image 581
Brandon Zamudio Avatar asked Jun 08 '17 18:06

Brandon Zamudio


4 Answers

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.

like image 93
EpicPandaForce Avatar answered Nov 02 '22 02:11

EpicPandaForce


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();
like image 24
Sanjay Kushwah Avatar answered Nov 02 '22 01:11

Sanjay Kushwah


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.

like image 36
A.jiji Avatar answered Nov 02 '22 00:11

A.jiji


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()
like image 38
Aditya Avatar answered Nov 02 '22 02:11

Aditya