Search code examples
androidnestedrealmrealm-list

RealmList with Android


Items upon inserting

Items upon retrieving

So here is the thing:

I have an Object Product which extends RealmObject. Inside the Product object, there is an attribute: RealmList. Bundle also extends RealmObject.

Inside the Bundle Object, there is an attribute: RealmList. ProductBundle extends RealmObject.

Now all those lists are not empty nor null by the time they should be inserted.

After insertion, if I query Realm for a list of Products, I will receive a list that has a list of RealmList. However, inside each of the Bundle items, the RealmList< ProductBundle> productBundles is always empty.

class Product extends RealmObject{
   RealmList<Bundle> bundles= new RealmList<Bundle>();
   boolean isLocallyAddedToCart;
}

class Bundle extends RealmObject{
  RealmList<ProductBundle> productsBundles = new RealmList<ProductBundle>();
}

class ProductBundle extends RealmObject{
  String title;
}

Any thoughts on that??

Query:

RealmResults<Product> cartItem = realm.where(Product.class).equalTo("isLocallyAddedToCart", true).findAll();

Inserting:

public void insertAddToCart(@NonNull ArrayList<Product> items) {
    try {
        Realm realm = getRealmInstance();
        realm.beginTransaction();
        realm.insertOrUpdate(items);
        realm.commitTransaction();
        realm.close();
    } catch (Exception ex) {
        ex.getStackTrace();
    }
}

Handling the objects:

RealmList<BundleProductOption> bundleProductOptions = new RealmList<>();
 private SparseArray<List<ProductBundle>> optionsFinalSelection = new SparseArray<>();
BundleProductOption bundleProduct = new BundleProductOption();                 

bundleProduct.setDefaultTitle(bundleProductOption.getDefaultTitle());

bundleProduct.setOptionId(bundleProductOption.getOptionId());  

bundleProduct.setParentId(bundleProductOption.getParentId());                          
bundleProduct.setRequired(bundleProductOption.getRequired());
bundleProduct.setType(bundleProductOption.getType());
RealmList<ProductBundle> productBundles = new RealmList<>();
productBundles.addAll(optionsFinalSelection.get(i));
bundleProduct.setProductsBundle(productBundles);
product.setSelectedOptions(bundleProductOptions);

Solution

  • you must manage your insertion with ID as a primary key in each model. when u insert or update u must use a primary key for saving all states of your data, and then u can do not use them, but realm need them for arrange insert or update method.

    keep me updated with your issue .