Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Realm for objects by IDs provided in a collection

Tags:

android

realm

I have a List<String> ids and I want all the FooRealmObjects that have the ID field included in the ids list.

I could iterate through the ids list and query objects by ID, but I was hoping there is a one-liner for this, like :

realm.where(Foo.class).in("id", ids).findAll();

Any ideas?

like image 595
Tudor Luca Avatar asked Mar 14 '23 23:03

Tudor Luca


2 Answers

Now realm already support the feature you want.

Added in Realm Java 1.2.0. (https://github.com/realm/realm-java/issues/841)

Now you can do exactly what you want:

realm.where(Foo.class).in("id", ids).findAll();
like image 161
Dan Meng Avatar answered Mar 17 '23 13:03

Dan Meng


As Jeremy mentioned, querying with a list of parameters is not possible (for now), but his answer does not work at all.

This is the workaround I used:

    List<String> ids = ...;

    Realm realm = Realm.getInstance(mContext);
    RealmQuery<Foo> query = realm.where(Foo.class);

    for (int i = 0; i < ids.size() - 1; i++) {
        query = query.equalTo("id", ids.get(i)).or();
    }
    query = query.equalTo("id", ids.get(ids.size() - 1));

    RealmResults<Foo> foos = query.findAll();
like image 29
Tudor Luca Avatar answered Mar 17 '23 12:03

Tudor Luca