简体   繁体   中英

How to delete realm list in Realm Database

I'm having a Realm class called Sale . I had a list of objects called allSales for Sale class. Now I want to delete some objects in Sale Realm class.

    RealmResults<Sale> allSales = realm.where(Sale.class).findAll();
    RealmList<Sale> toBeDeleted = new RealmList<Sale>();

    for(Sale sale : allSales){
        String salesDate = sale.getSaleDate();
        if(salesDate.equals("01-01-2017")) {
            toBeDeleted.add(realm.copyToRealm(sale));
        }
    }

    realm.beginTransaction();
    toBeDeleted.clear();
    realm.commitTransaction();

The data was not cleared in Sale class instead toBeDeleted list only cleared.

You can use RealmList.deleteFromRealm() / RealmList.deleteAllFromRealm() to remove items from both the list and Realm. See the methods in API docs here: https://realm.io/docs/java/latest/api/io/realm/RealmList.html

You have to call this method from realm transaction...

realm.executeTransaction(new Realm.Transaction() {
                                    @Override
                                    public void execute(Realm realm) {
                                        saleRalmList.deleteLastFromRealm();// use to delete all

                                        //**OR** use in for loop to delete perticulr record as a location
                                        saleRalmList.deleteFromRealm(location);

                                    }
                                });

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