Reputation: 48
I've started using Realm for Android. I'm lovin' it so far, but I'm having some problems trying to understand how to use correctly the "copyToRealmOrUpdate".
I will receive a JSON (that I'm mapping into a Contact RealmObject Array) with a X "contacts" every time I open the App, and I want to insert them on the Realm DB if they don't exist, or update them in case they do.
The problem here is that I'm getting a Primary Key error everytime I do that, so it seems it's always inserting those records: "Primary key constraint broken. Value already exists: row_id1"
RealmObject has a @PrimaryKey "Id" declared. In this test scenario I'm trying to add the same 5 records two times.
This is my insert code:
mRealm.beginTransaction();
Contact contact;
for (int i = 0; i < contactArrayList.size(); i++) {
contact = mRealm.createObject(Contact.class);
contact.setId(contactArrayList.get(i).getId());
contact.setFirstName(contactArrayList.get(i).getFirstName());
...
mRealm.copyToRealmOrUpdate(contact);
}
mRealm.commitTransaction();
Any help would be much appreciated, thank you!
Upvotes: 1
Views: 1436
Reputation: 20126
It is because you are combining mRealm.createObject()
with mRealm.copyToRealmOrUpdate()
. These two concepts are really orthogonal.
Realm operates with a concept of "managed" and "standalone objects". Standalone objects is objects that are created using the normal new
operator and are converted to managed objects when you use one of the mRealm.copyXXX
methods.
mRealm.createObject()
on the other hand creates the managed object immediately and set all fields to default values. For classes with a @PrimaryKey
this can be a problem since setting the default value for the primary key (0 or "") might clash with an already existing primary key, and then you will get the error you see.
In your case doing the following instead should work:
mRealm.beginTransaction();
Contact contact;
for (int i = 0; i < contactArrayList.size(); i++) {
contact = new Contact();
contact.setId(contactArrayList.get(i).getId());
contact.setFirstName(contactArrayList.get(i).getFirstName());
...
mRealm.copyToRealmOrUpdate(contact);
}
mRealm.commitTransaction();
Upvotes: 4