Realm query with List

北战南征 提交于 2019-11-29 13:51:15

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();

Since the Realm database has added RealmQuery.in() with the version 1.2.0

I suggest using something like this.

//Drinks
public class Drinks extends RealmObject {
@PrimaryKey
private String id;
private String name;
private String countryId;

//getter and setter methods
}

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

//getter and setter methods
}

The code to use inside activity/fragments to retrieve drink list

String[] countryIdArray = new String[] {"1","2","3"} //your string array
RealmQuery<Drinks> realmQuery  = realm.where(Drinks.class)
            .in("countryId",countryIdArray);
RealmResults<Drinks> drinkList = realmQuery.findAll();

To match a field against a list of values, use in. For example, to find the names “Jill,” “William,” or “Trillian”, you can use in("name", new String[]{"Jill", "William", "Trillian"}). The in predicate is applicable to strings, binary data, and numeric fields (including dates).

Doc.-> https://realm.io/docs/java/latest#queries

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!