领域:创建(或发布)Realm对象的更好方法是什么?

时间:2016-04-04 16:15:23

标签: android realm

我在Android上做一个表格样本,用户可以用她的狗创建一个人(一对一的关系),所以我设计了一个人和狗模型,其中每个人对象都有一个狗对象(在人物)。所以,当我点击按钮用他的狗创建一个人对象时Android会抛出这个错误:

  

RealmPrimaryKeyConstraintException:值已存在:

我用来创建Realm对象的方法是copyToRealm

realm.copyToRealm(persona.getPerro());
realm.copyToRealm(persona);

但是在研究解决方案后,我看到人们使用copyToRealmOrUpdate

realm.copyToRealmOrUpdate(persona.getPerro());
realm.copyToRealmOrUpdate(persona);

当我使用它时,我的应用程序正常运行。但我还是有些疑惑。我更愿意知道我应该考虑使用copyToRealmOrUpdate而不是copyToRealm应该考虑哪些事情,因为现在我正在进行应用程序开发,我想将Realm与我将使用的数据库一起使用(因为我正在做人和狗样本来测试如何使用Realm因为那时我将不得不开发一个具有很多字段和objetcs之间关系的应用程序。)

为什么会发生此错误(RealmPrimaryKeyConstraintException: Value already exists: )?

创建RealmObjects的更好方法是什么?

PD:每次使用

 copyToRealm or copyToRealmOrUpdate

方法,我将其与beginTransaction()commitTransaction()

括起来

1 个答案:

答案 0 :(得分:3)

Assuming you have primary key as integer

0 is the default value for int fields, so if you have a RealmObject with 0 as the value for your code field, it means that realm.createObject(YourRealmClass.class) will fail with the error you mentioned

as it will create an object with the default value.

What is the better way to create RealmObjects?

copyToRealmOrUpdate() is better to use as it first checks if record exists or not . If record exists then it will update if record does not exits it will insert new record .