检索一个RealmObject并将其设置为另一个RealmObj

检索一个RealmObject并将其设置为另一个RealmObj

本文介绍了从Realm检索一个RealmObject并将其设置为另一个RealmObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Realm上遇到问题,导致每次我尝试将RealmObject设置为另一个后,它都会因NullPointerException崩溃而崩溃.

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.

例如.

    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();

我不确定我还能采取什么措施来防止这种情况的发生.我需要执行此操作的原因是需要在一个地方创建Person对象,而我想在另一个地方添加动物.

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.

我发现这可行:

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

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

这对于简单的数据结构是很好的.但是我正在使用包含两个或三个其他RealmObjects的Realm对象,并像这样操作它们似乎是很多不必要的工作.

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.

谢谢

推荐答案

Pet = new Pet()将创建一个尚未由Realm管理的独立对象.这就是personFromRealm.setPet(pet)崩溃的原因.但是,这里的错误消息根本不是用户友好的...

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...

尝试:

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

或更简单:

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 是为了获得更好的异常消息而创建的.

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

这篇关于从Realm检索一个RealmObject并将其设置为另一个RealmObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 19:45