Ambran
Ambran

Reputation: 2627

Initialize Realm object with @PrimaryKey 0 (zero) fails on second object

I'm experiencing some weird behaviour when trying to initialize a simple Realm object. I have a JSONArray which looks like that:

[{"id":0,"name":"Biatrix"},{"id":1,"name":"Bill"},{"id":2,"name":"O-ren"}]

I have the following simple Realm class:

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;

public class Assassin extends RealmObject {
    @PrimaryKey
    private int id;

    @Required
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Here is how I try to populate the class (in Kotlin):

val assassins = viperData.getJSONArray("assassins")

for (i in 0..(assassins.length() - 1)) {
    val item = assassins.getJSONObject(i)

    var assassin = realm.createObject(Assassin::class.java)
    assassin.setId(item.getInt("id"))
    assassin.setName(item.getString("name"))
}

The first item which has id=0 is created fine, but the in the second item I get an exception io.realm.exceptions.RealmPrimaryKeyConstraintException: Value already exists: 0. Then I thought oh ya, the object is created pr. default with a id=0 and only afterwords I change the value to something else. It's failing because it allready has an item with the value 0. So I set the id=-1 in the class:

...
public class Assassin extends RealmObject {
    @PrimaryKey
    private int id = -1;
...

... but still get the same exception.

Is this a bug or am I missing something here?

Update

I removed the @PrimaryKey annotation and the class populated correctly. Just to show that the values are unique, here is a shot of the realm class containing the values (the actual values - no assassins here...):

enter image description here

Upvotes: 0

Views: 793

Answers (1)

Wukash
Wukash

Reputation: 666

From realm documentation:

When calling Realm.createObject(), it will return a new object with all fields set to the default value. In this case, there might be a conflict with an existing object whose primary key field is the default value. To avoid this, it is suggested to create a standalone object, set values of the fields, and then copy it to Realm by copyToRealm() method.

Upvotes: 1

Related Questions