Realm-java: Realm Query for List

Created on 19 Jul 2017  路  4Comments  路  Source: realm/realm-java

I have a product Model Like this

public class Product
{
private String title;
private RealmList<Meta> meta;

public class Meta {
public String key;
public String value;
     }
}

Model is populated from below JSON.

[{
    "title": "BBQ chicken",
    "meta": [{
            "key": "content",
            "value": "Chicken"

        },
        {
            "key": "protein",
            "value": "Chicken"
        }
    ]

}, {
    "title": "Beef BBQ",
    "meta": [{
            "key": "content",
            "value": "Beef"

        },
        {
            "key": "protein",
            "value": "good"
        }, {
            "key": "ingredient",
            "value": "chicken"
        }
    ]

}]

What I need is, filter all products which have content="chicken". So I ended up in writing a query like this.

realm.where(Product.class).equalTo("meta.key","content").equalTo("meta.value","chicken").findAll().
But I ended up in result set with both the products. How can I do something like this say, I need only the products which has key="content" and value="chicken".

T-Help

Most helpful comment

realm.where(Product.class)
         .equalTo("meta.key","content")
         .findAll()
         .where()
         .equalTo("meta.value","chicken")
         .findAll()

All 4 comments

realm.where(Product.class)
         .equalTo("meta.key","content")
         .findAll()
         .where()
         .equalTo("meta.value","chicken")
         .findAll()

@Zhuinden thanks , Awesome, will try this

@pollux- You can also read this relevant section in the docs: https://realm.io/docs/java/latest/#link-queries

Awesome, working as expected 馃憤

 final Realm dbInstance = DbManager.getInstance().getDBInstance();
        dbInstance.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {

                try {
                    RealmResults<TestProduct> product = dbInstance.where(TestProduct.class).findAll();
                    if (product.size() ==0) {
                        final InputStream testJson = getAssets().open("test_json");
                        dbInstance.createAllFromJson(TestProduct.class, testJson);
                    }
                    RealmResults<TestProduct> all = dbInstance.where(TestProduct.class).equalTo("meta.key","content").findAll().where().equalTo("meta.value","chicken").findAll();
                    int size = all.size();

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bryanspano picture bryanspano  路  3Comments

wyvern610 picture wyvern610  路  3Comments

gpulido picture gpulido  路  3Comments

David-Kuper picture David-Kuper  路  3Comments

jjorian picture jjorian  路  3Comments