Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm on Android - How to select multiple objects by list of ids (@PrimaryKey)?

Tags:

android

realm

I'm building an Android app with the Realm database.

I have a RealmObject subclass called Article which has an id field (it's and int and also a @PrimaryKey). I would like to pass to a query a list of ints (a Set, int[], or whatever) of article id's and retrieve only those articles.

In SQL would be like this:

SELECT *
FROM `table`
where ID in (5263, 5625, 5628, 5621) 

I've seen it's possible to do this in iOS in this StackOverflow question.

How can I do this in Android? Thanks!

Edit: Just to inform, I also asked this on the GitHub repo here.

like image 461
Albert Vila Calvo Avatar asked Nov 11 '15 13:11

Albert Vila Calvo


2 Answers

Update:

Realm 1.2.0 has added RealmQuery.in() for a comparison against multiple values. The documentation details all the available overloads. This one is the method we can use if our ids are Integers:

public RealmQuery<E> in(String fieldName, Integer[] values)

Original answer:

The answer from @ChristianMelchior returns all articles if the list of ids is empty. I want it to return an empty RealmResults<Article>. That's what I've ended up doing:

Set<Integer> articleIds = this.getArticleIds();
RealmQuery<Article> query = realm.where(Article.class);
if (articleIds.size() == 0) {
    // We want to return an empty list if the list of ids is empty. 
    // Just use alwaysFalse
    query = query.alwaysFalse();
} else {
    int i = 0;
    for (int id : articleIds) {
        // The or() operator requires left hand and right hand elements. 
        // If articleIds had only one element then it would crash with
        // "Missing right-hand side of OR"
        if (i++ > 0) {
            query = query.or();
        }
        query = query.equalTo("id", id);
    }
}
return query.findAll();
like image 99
Albert Vila Calvo Avatar answered Oct 24 '22 04:10

Albert Vila Calvo


Now realm v 1.2.0 support RealmQuery.in() for a comparison against multiple values.

like image 23
mouness2020 Avatar answered Oct 24 '22 03:10

mouness2020