Search code examples
androidrealm

Android realm. Passing RealmObject as parameter to constructor. Null values fields


It seems like RalmObject sets its fields to default values when it passes to constructor of other RealmObject (look at comments in code below). Simple workaround is don't pass object to constructor and assign fields after object is created. But I actually don't understand how's it even possible. So my question is: Can anybody explain what's going on, please? And in which situations else I should be aware of behavior like that while working with Realm?

That's simple example of code which reproduces the issue:

 realm = Realm.getDefaultInstance();
 realm.executeTransaction(new Realm.Transaction() {
      @Override
      public void execute(Realm realm) {
            Stock stock1 = new Stock();
            stock1.id = "stock1";
            managedStock = realm.copyToRealm(stock1);
      }
});
//output here: managedStock.id = stock1
Log.d("myLogs", "managedStock.id = " + managedStock.id);
Goods goods = new Goods(managedStock);

And in constructor of Goods object passed managedStock has id == null, how's that possible?

public class Goods extends RealmObject {
    @PrimaryKey
    public String id;
    public Stock stock;

    public Goods() {}

    public Goods(Stock s) {
        //output here: s.id == null
        Log.d("myLogs", "s.id == " + s.id);
    }
}

And Stock object, just in case

public class Stock extends RealmObject {
    @PrimaryKey
    public String id;
    public String name;
}

Some additional info: realm 1.2.0 , android 5.0, device Samsung Galaxy S4

Thanks in advance!


Solution

  • This sounds like a Realm Transformer issue, so I made an issue on the realm-java github issues.

    In the meantime, I recommend using getters/setters instead of direct field access.