简体   繁体   中英

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 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 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.

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.

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()

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM