Search code examples
javaandroidrealmupdating

Setting a RealmObject to another RealmObject after retrieving it from Realm


I am having an issue with Realm which is causing it to crash with a NullPointerException everytime I try and set a RealmObject to another after it's been stored.

Eg.

    Person person = new Person();
    person.setName("Martha");
    Realm realm = Realm.getInstance(this);
    realm.beginTransaction();
    realm.copyToRealm(person);
    realm.commitTransaction();

    Person personFromRealm = realm.where(Person.class).findFirst();

    realm.beginTransaction();
    Pet pet = new Pet();
    pet.setType("dog");
    personFromRealm.setPet(pet); <--- This line will crash
    realm.commitTransaction();

I am not sure what else I can do to prevent this from happening. The reason i need to do this is the Person object needs to be created in one place and I want to add the animals at another.

I found this works:

    Realm realm = Realm.getInstance(this);
    Person personFromRealm = realm.where(Person.class).findFirst();

    realm.beginTransaction();
    Pet pet = personFromRealm.getPet();
    pet.setType("dog");
    realm.commitTransaction();

This is fine for simple data structures. But I am using Realm objects which contain two or three other RealmObjects and manipulating them like this seems like a lot of unnecessary work.

I just want to know if I am missing something. Or if there there is an easier way to do this. Any help would be greatly appreciated.

Thanks


Solution

  • Pet = new Pet() will create a standalone Object which is not managed by Realm yet. And it is the reason personFromRealm.setPet(pet) crash. However, the error message here is not user friendly at all...

    Try:

    Pet pet = new Pet();
    pet.setType("dog");
    pet = realm.copyToRealm(pet);
    personFromRealm.setPet(pet);
    

    or simpler:

    Pet pet = realm.createObject(Pet.class);
    pet.setType("dog");
    personFromRealm.setPet(pet);
    

    Both of them need to be in a transaction.

    https://github.com/realm/realm-java/issues/1558 is created for a better exception message.