Android: Realm understand LinkingObjects

android, java, orm, realm

Solution

You are looking for

public class Product extends RealmObject
{
    @PrimaryKey
    private int prodId;

    @Required
    private String name;

    private RealmList<ProductItem> productItems;

    //@LinkingObjects("productParent")
    //private final RealmResults<ProductItem> linkProductItems = null;
    ...
    ...
    ...
}

public class ProductItem extends RealmObject
{
    @PrimaryKey
    private String primaryKey;

    private int prodId;

    private int prodItemId;

    private String itemCode;

    private double price;

    //private Product productParent;    

    @LinkingObjects("productItems")   // <-- !
    private final RealmResults<Product> productParents = null; // <-- !
    ...
    ...
    ...
    public RealmResults<Product> getProductParents() // <-- !
    {
        return productParents;
    }
}

Problem

I need help on LinkingObjects in Realm. Please look at these simple codes: ``` public class Product extends RealmObject { @PrimaryKey private int prodId; @Required private String name; private RealmList<ProductItem> productItems; @LinkingObjects("productParent") private final RealmResults<ProductItem> linkProductItems = null; ... ... ... } public class ProductItem extends RealmObject { @PrimaryKey private String primaryKey; private int prodId; private int prodItemId; private String itemCode; private double price; private Product productParent; ... ... ... public Product getProductParent() { return productParent; } } ``` Then, I added the sample data by doing this: ``` realm.beginTransaction(); Product prod = new Product(); prod.setProdId(1); prod.setName("Test"); prod = realm.copyToRealm(prod); ProductItem prodItem = new ProductItem(); prodItem.setProdId(prod.getProdId()); prodItem.setProdItemId(1); prodItem.setItemCode("00231"); prodItem.setPrice(9.95); prodItem.getProductItems().add(realm.copyToRealm(prodItem)); realm.commitTransaction(); ``` Now, from what I understand LinkingObjects allows you to refer back to your parent? But the following code will fails: ``` String sOutput = ""; for (ProductItem prodItem : realm.where(ProductItem.class).findAll()) sOutput += prodItem.getProductParent().getName() + "\n"; ``` The problem is bqItem.getProductParent() is NULL. My question is, have I done LinkingObjects correctly? If not, can you help me? Thanks

Original source