Home > OS >  ROOM Database: I can't autoGenerate my primary key
ROOM Database: I can't autoGenerate my primary key

Time:10-20

this is my code and I think it's 100% correct

@Serializable
@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    var userID: Int = 1,
    var fullName: String = "Missing",
    var email: String = "Missing",
    var password: String = "Missing",
    var phone: Long = -1,
    var profileImage: String = "Missing",
    var userType: Int = -1,
) {

    constructor(
        userID: Int = 1
    ) : this(
        fullName = "Missing",
        email = "Missing",
        password = "Missing",
        phone = -1,
        profileImage = "Missing",
        userType = -1,

        )
}

also, why tableName & autoGenerate not showing in blue color enter image description here

Because the code was working for me before, but now I don't know why it doesn't work now

CodePudding user response:

remove default id you've set in constructor, leave it for fulfil by database (when it autogenerate id for you)

@PrimaryKey(autoGenerate = true)
val userID: Int, // no = 1

also remove your second constructor and keep all your variables as final (thus val, not var)

edit: sample

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true) val userID: Int,
    val fullName: String = "Missing",
    val email: String = "Missing",
    val password: String = "Missing",
    val phone: Long = -1,
    val profileImage: String = "Missing",
    val userType: Int = -1,
)

CodePudding user response:

I discovered the problem

userID: Int = 0 no 1

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    var userID: Int = 0,
    var fullName: String = "Missing",
    var email: String = "Missing",
    var password: String = "Missing",
    var phone: Long = -1,
    var profileImage: String = "Missing",
    var userType: Int = -1,
) {

    constructor(
        userID: Int
    ) : this(
        userID,
        fullName = "Missing",
        email = "Missing",
        password = "Missing",
        phone = -1,
        profileImage = "Missing",
        userType = -1,
        )
}
  • Related