Unable to change the value of primary key in Realm Android

3.3k views Asked by At

I'm trying to change the current value of primary key to another. Like this.

realm?.executeTransactionAsync ({ realm ->
    val teamRealmObj = realm?.where(Team::class.java)?.equalTo("name", oldTeamName)?.findFirst()
        teamRealmObj?.name = newTeamName
    })

Here name attribute is a primary key.

I'm getting this error.

Failed Primary key field 'name' cannot be changed after the object was created.

How can I achieve this? Do I have to make a copy(only different name attribute) and delete the old one? This will cause headache in one to many or many to many relations as the new object must be replaced every where in the database.

Need a better way to do this. Thank you if anybody can help me to figure this out.

1

There are 1 answers

1
Harv On

This piece of code fixed my issue.

realm?.executeTransactionAsync ({ realm ->
        val teamRealmObj = realm.where(Team::class.java)?.equalTo("name", oldTeamName)?.findFirst()
        val newTeamObj = realm.copyFromRealm(teamRealmObj)
        newTeamObj?.name = newTeamName
        realm.copyToRealmOrUpdate(newTeamObj)
        teamRealmObj?.deleteFromRealm()
    }

There is no need to recreate the links.

realm.copyToRealmOrUpdate(newTeamObj)

This line is automatically doing this.