Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

android - Realm query with List

I'm using realm to store my data on Android. Awesome framework! Now the only problem I'm now having is:

I got a array list strings with id's of Countries in my database.

Now I retrieve my Drinks that contains a relationship to countries.

Is there a way that I could to do a query like this:

String [] ids;

realm.where(Drinks.class).equalsTo("country.id", ids);

Something like that?

Or do I really need to do a query to get me all drinks and then filter the list manually?

EDIT:

My classes:

public class Drinks extends RealmObject {
    @PrimaryKey
    private String id;
    private String name;
    private Country country;
}

public class Country extends RealmObject {
    @PrimaryKey
    private String id;
    private String name;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you want to do is possible with link queries in theory (searching for "country.id"), however link queries are slow. Also you'd need to concatenate a bunch of or() predicates together, and I would not risk that with a link query.

I would recommend using the following

public class Drinks extends RealmObject {
    @PrimaryKey
    private String id;
    private String name;
    private Country country;
    @Index
    private String countryId;
}

public class Country extends RealmObject {
    @PrimaryKey
    private String id;
    private String name;
}

And when you set the Country in your class, you also set the countryId as country.getId().

Once you do that, you can construct such:

RealmQuery<Drinks> drinkQuery = realm.where(Drinks.class);
int i = 0;
for(String id : ids) {
    if(i != 0) {
        drinkQuery = drinkQuery.or();
    }
    drinkQuery = drinkQuery.equalTo("countryId", id);
    i++;
}
return drinkQuery.findAll();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...