Reputation: 527
I'm doing a sample of a form on Android where the user can create a person with her dog (one to one relationship), so I designed a person and dog model where each person object has a dog object (inside of person object). So when I click on the button to create a person object with his dog Android throws me this error:
RealmPrimaryKeyConstraintException: Value already exists:
The method that I used to create Realm Objects is copyToRealm
realm.copyToRealm(persona.getPerro());
realm.copyToRealm(persona);
But After a research for a solution I looked that people use copyToRealmOrUpdate
realm.copyToRealmOrUpdate(persona.getPerro());
realm.copyToRealmOrUpdate(persona);
And when I used it, My app worked. But I still have some doubts. I prefer to know what things I should consider to use copyToRealmOrUpdate
instead of copyToRealm
because now I'm working in an app development and I want to use Realm with the DB that I will use (Because of that I'm doing the person and dog sample to test how to work with Realm because then I will have to develop an app with a lot of fields and relationships between objetcs).
Why this error happens (RealmPrimaryKeyConstraintException: Value already exists:
)?
What is the better way to create RealmObjects?
PD : each time i use
copyToRealm or copyToRealmOrUpdate
method, I enclose it with beginTransaction()
and commitTransaction()
Upvotes: 0
Views: 758
Reputation: 27505
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 .
Upvotes: 3