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

前端 未结 5 1273
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 21:25

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

I have a RealmObject subclass called Article which has an id field (it\'s an

5条回答
  •  伪装坚强ぢ
    2021-02-18 21:55

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

    . That's what I've ended up doing;

    Set articleIds = this.getArticleIds();
    RealmQuery
    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();

提交回复
热议问题