在Android领域 - 如何选择由IDS(@PrimaryKey)的列表中选择多个对象? [英] Realm on Android - How to select multiple objects by list of ids (@PrimaryKey)?

查看:306
本文介绍了在Android领域 - 如何选择由IDS(@PrimaryKey)的列表中选择多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个Android应用程序与数据库领域

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

文章叫做 RealmObject 子类,有一个 ID 字段(它和 INT ,也是一个 @PrimaryKey )。我想传递给查询 INT S(一设置 int的列表[] ,或其他)文章编号的,并且只检索这些条款。

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.

在SQL会是这样的:

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

我已经看到了它有可能做到这一点iOS中的这个计算器问题

我怎样才能做到这在Android中?谢谢!

How can I do this in Android? Thanks!

编辑:只是为了告知,我也问过这个在GitHub库的这里

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

推荐答案

这@ChristianMelchior答案返回所有文章,如果ID列表是空的。我希望它返回一个空 RealmResults<物品> 。这就是我最后做;

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 search for an id that does not exist.
    query = query.equalTo("id", -30000);
} 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();

这篇关于在Android领域 - 如何选择由IDS(@PrimaryKey)的列表中选择多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆