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

编程入门 行业动态 更新时间:2024-10-28 14:26:48
本文介绍了从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); realmmitTransaction(); Person personFromRealm = realm.where(Person.class).findFirst(); realm.beginTransaction(); Pet pet = new Pet(); pet.setType("dog"); personFromRealm.setPet(pet); <--- This line will crash realmmitTransaction();

我不确定我还能采取什么措施来防止这种情况的发生. 我需要执行此操作的原因是需要在一个地方创建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"); realmmitTransaction();

这对于简单的数据结构是很好的.但是我正在使用包含两个或三个其他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.

github/realm/realm-java/issues/1558 是为了获得更好的异常消息而创建的.

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

更多推荐

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

本文发布于:2023-08-05 20:39:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307941.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   并将其   Realm   RealmObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!