Setting a RealmObject to another RealmObject after retrieving it from Realm

人走茶凉 提交于 2019-12-12 03:19:08

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/33010688/setting-a-realmobject-to-another-realmobject-after-retrieving-it-from-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!