Kevin van Mierlo
Kevin van Mierlo

Reputation: 9814

Android Realm: Primary key constraint broken. Value already exists: 0

I'm working a lot with Realm nowadays. I like it a lot! But one thing that's really annoying is that I cannot set my primary key to zero when using copyToRealmOrUpdate. I get my id back from a server. The first id is zero. So my app immediately crashes saying: Primary key constraint broken. Value already exists: 0. If this would be a different number than it works just fine, but it crashes on zero. Is this a bug or can anybody help me?

Thanks!

Upvotes: 4

Views: 1773

Answers (1)

Christian Melchior
Christian Melchior

Reputation: 20126

Christian from Realm here. 0 is a bit problematic because it is also the default value for integers. Meaning that if you do have 0 as an actual value, you will run into problems using API's like Realm.createObject(). That said, we just fixed a bug using Realm.copyToRealmOrUpdate() that covers you exact use case: https://github.com/realm/realm-java/pull/995

It has already been merged to master so should be part of our -SNAPSHOT release, but hasn't been properly released yet. You can try it using:

 repositories {
        jcenter()
        maven {
            url 'http://oss.jfrog.org/artifactory/oss-snapshot-local'
        }
    }

    compile 'io.realm:realm-android:0.80.1-SNAPSHOT'

Upvotes: 6

Related Questions