简体   繁体   中英

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!

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

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