简体   繁体   中英

How to Clear the RealmResults<> of a particular Query while Filtering through the Realm in Android?

I am applying filters on realm using RealmResults<>.

I begin to do like this -

RealmResults<data> filteredRealmResults;
List<data> tranfilteredlist;

private OrderedRealmCollectionChangeListener<RealmResults<data>> filteredTransChangeListener =
            new OrderedRealmCollectionChangeListener<RealmResults<data>>() {
                @Override
                public void onChange(RealmResults<data> results, OrderedCollectionChangeSet changeSet) {

                    Log.d("realm", "filteredRealmResults.size():" + filteredRealmResults.size());

                    tranfilteredlist = results;
                    initFilterAdapter();

                }
            };

Now I want to delete the filteredRealmResults . I did like this -

void deleteFilteredRealmResults() {

        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                // Delete all matches
                filteredRealmResults.deleteAllFromRealm();
            }
        });
    }

After doing this my data in the realm got deleted. So I just try to delete the tranfilteredlist but it throws an exception that it does not support .clear();

I want to clear if from the memory whatever is holder the query data. Correct me if I am wrong or doesn't understand or just worrying too much.

I read This class holds all the matches of a RealmQuery for a given Realm. The objects are not copied from the Realm to the RealmResults list, but are just referenced from the RealmResult instead. This saves memory and increases speed.

I want to clear if from the memory whatever is holder the query data. Correct me if I am wrong or doesn't understand or just worrying too much.

Once you invoke filteredRealmResults.deleteAllFromRealm , it will clear the internal resultant elements object (which holds the elements) and as you know, resultant objects are reference so data will be deleted from realm database too. Hence, there is no need to call clear on the RealmResults object.

You can verify this by calling filteredRealmResults.size() after deletion, it will return 0 .

I just try to delete the tranfilteredlist but it throws an exception that it does not support .clear();

It is the expected behaviour as clear has been deprecated so don't use it.

Why deprecated?

  1. deleteAllFromRealm automatically clears the list so no need to call it again explicitly.
  2. Calling clear on RealmResults object will result in deletion of data from database, can cause unexpected behaviour if the user is not aware so API is being modified to avoid unexpected behaviours.

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