Linked Questions

Popular Questions

Realm Query not giving correct results

Asked by At

I have the following data structure which consist in a list of providers, having products and each product has different types

Provider Class

public class Provider extends RealmObject {

    @SerializedName("id")
    @PrimaryKey
    public int providerId;
    public String name;
    public RealmList<Product> products;

}

Product Class

public class Product extends RealmObject {

    @SerializedName("id")
    @PrimaryKey
    public int productId;
    public String name;
    public RealmList<ProductType> types;

}

Product type class

public class ProductType extends RealmObject {

    @SerializedName("id")
    @PrimaryKey
    public int productTypeId;
    public String name;
    public Packaging packaging; }

Here is a JSON example of what is loaded into realm:

{
  "providers": [{
      "id": 1,
      "name": "PROVIDER_1",
      "products": [{
        "id": 10,
        "name": "Banana",
        "types": [{
            "id": 101,
            "name": "Costa rica",
            "packaging": {
              "isFree": true,
              "value": 0
            }
          },
          {
            "id": 102,
            "name": "Brasil",
            "packaging": {
              "isFree": true,
              "value": 0
            }
          }
        ]
      }]
    },{
      "id": 4,
      "name": "PROVIDER_2",
      "products": [{
        "id": 10,
        "name": "Banana",
        "types": [{
            "id": 103,
            "name": "Ecuador Prem",
            "packaging": {
              "isFree": true,
              "value": 0
            }
          }
        ]
      },
      {
        "id": 21,
        "name": "Apple",
        "types": [{
            "id": 212,
            "name": "Red del",
            "packaging": {
              "isFree": true,
              "value": 0
            }
          }
        ]
      }]
    }

    ]
}

So, the problem I am having is appear when I try to fetch types of Bananas using the following query

RealmResults<Provider> results = mRealm.where(Provider.class).equalTo("providerId", providerId).findAll();
Product product = results.where().equalTo("providerId", providerId).findFirst().products.where().equalTo("productId", productId).findFirst();
RealmList<ProductType> types = product.types;

the list of Types returned is giving me always the types of the second provider. In current example, I am getting "Ecuador Prem" even if I am requesting provider id 1 which is PROVIDER_1, and that provider must return as types "Costa rica" and "Brasil".

Related Questions