How to delete first n rows in realm

1.1k views Asked by At

Suppose there is a table called RecentViewItem which stores recently viewed items by user. I want to keep only first 10 recently viewed items by deleting all other items. My query is like this:

RealmResults<RecentViewItem> results = 
    realm.where(RecentViewItem.class)
         .findAllSorted("updatedAt", Sort.DESCENDING);
// What to do next ?
2

There are 2 answers

5
EpicPandaForce On
RealmResults<RecentViewItem> results = realm.where(RecentViewItem.class).findAllSorted("updatedAt", Sort.DESCENDING);
for(int i = 0, size = results.size(); i < 10 && i < size; i++) {
    RecentViewItem recentViewItem = results.get(i);
    recentViewItem.deleteFromRealm();
}
0
LordParsley On

Since Realm for Java lazy loads its data, there isn't a LIMIT query which adds a bit of work. I query all the data sorted by a timestamp (in your case updatedAt).

Realm realm = Realm.getDefaultInstance();
final RealmResults<RecentViewItem> results = realm.where(RecentViewItem.class).findAllSorted("timestamp", Sort.DESCENDING);

I check whether it's over my limit and, if it is, get the result on the threshold so I can get its timestamp. Then I query against that threshold timestamp and delete all the results from before it.

if (results.size() > UPPER_LIMIT) {
    RecentViewItem firstOverLimit = results.get(TRUNCATE_LIMIT);
    // Assuming a system time. Maybe your updatedAt is a date. Could use an id too.
    long threshold = firstOverLimit.timestamp;
    final RealmResults<RecentViewItem> resultsToDelete = realm.where(RecentViewItem.class).lessThanOrEqualTo("timestamp", threshold).findAll();
    Log.d(TAG, "cleanUp: total "+ results.size() +
        "; over threshold of " + UPPER_LIMIT +
        "; truncating to " + TRUNCATE_LIMIT +
        "; deleting " + resultsToDelete.size() +
        "; all on or before "+ threshold);
    realm.executeTransaction(realm1 -> resultsToDelete.deleteAllFromRealm());
}

My TRUNCATE_LIMIT is half my UPPER_LIMIT so that this clean up does not run constantly as new records are added, but you can tune that however you like.

I'm also deleting the first record over the limit, but you can play with the boundary and retain it.

Also, my timestamp is quite exact but if your date is just "today" then you will get fuzzier results.