Search code examples
androidsqliterealmrealm-mobile-platformandroid-database

Android : Realm database delete all the records after first N records from the database


I've integrated Realm android to my project. I want to keep my table restriction to store max 100 records. If any new records come then check for if its limit increases to 100 then It should delete those records (101..N). The table should contain the last 100 records only.

Any help will be appreciable.

Thanks in advance!


Solution

  • There is no automatic way of doing this. But if you add a timestamp in your model class (say, created), you could add a listener and delete the old object. Something like:

    realmListener = new RealmChangeListener() { @Override public void onChange(Realm realm) { RealmResults<YourClass> objs; int nObjsToDelete; objs = realm.where(YourClass.class).sort(created).findAll(); nObjsToDelete = objs.size()-100; objs.limit(nObjectToDelete).findAll().deleteAllFromRealm(); } }; realm.addChangeListener(realmListener);