0

In the room database I want to auto generate id, I did the bellow code but I get UNIQUE constraint failed error.

How can i get the table to autogenerate id and I do not want to pass id

@Entity
data class OfflineDatax (
    @PrimaryKey(autoGenerate = true) val uid: Int = 0,
    @ColumnInfo(name = "requestJSON") val requestJSON: String?,
    @ColumnInfo(name = "requestCode") val requestCode: String?
) 

@Dao
interface OfflineDataDao {
    @Query("SELECT * FROM offlinedata")
    fun getOfflineData(): Flow<List<OfflineData>>

    @Insert()
    suspend fun insertOfflineData(offlineData: OfflineData)
}

This is how inserting data

libOfflineDataDao.insertOfflineData(OfflineData(1,"test", "test"))

Thanks R

BRDroid
  • 3,920
  • 8
  • 65
  • 143
  • 2
    Use `0` to auto generate ID for the inserted row. – Nicolas Jun 04 '20 at 17:08
  • Documentation supporting comment by @Nicolas: https://developer.android.com/reference/androidx/room/PrimaryKey#autoGenerate() – Bob Snyder Jun 04 '20 at 17:17
  • see these answers https://stackoverflow.com/a/44109830/11586761 and https://stackoverflow.com/questions/50558275/unique-constraint-failed-room-database-android – HGH806 Jun 04 '20 at 17:26
  • @Nicolas when i changed it to 0 it did work, thanks guys – BRDroid Jun 04 '20 at 17:34

1 Answers1

-1

we need the unique ID only to access the data but since you are just inserting the data and also you have set the default value as 0 to be inserted, Kotlin is smart enough to insert the data with just the rest two of the parameters. Please let me know if this has helped in any way.

libOfflineDataDao.insertOfflineData(OfflineData("test", "test")) 

This should work too.

Nitin Tej
  • 353
  • 1
  • 7