I have a problem, when i insert a new element to the table it gives me an exception: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DayCalorieData.date (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY), but i dont’t uderstand why. Because i set OnConflictStrategy.IGNORE. Here is code for my db:
Entity:
@Entity(
tableName = "dayNutrientAmount",
primaryKeys = ["date", "nutrientId"],
indices = [Index(value = ["date", "nutrientId"], unique = true)]
)
data class DayNutrientAmount(
val date: String,
val nutrientId: Int,
val receivedAmount: Int = 0,
)
Dao:
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertNewDayNutrient(dayNutrientAmount: DayNutrientAmount)
ViewModel:
fun insertNewDayNutrientAmount(nutrientId: Int, date: String) {
viewModelScope.launch(Dispatchers.IO) {
mainScreensRepositoryImpl.insertDayNutrientAmount(DayNutrientAmount(
date, nutrientId
))
}
}
Ui:
val nutrients = homeScreenVM
.getAllNutrients()
.collectAsState(initial = emptyList())
.value
LaunchedEffect(key1 = nutrients, key2 = selectedDate) {
nutrients.forEach { nutrient ->
homeScreenVM.insertNewDayNutrientAmount(nutrient.nutrientId, selectedDate)
}
}
I don’t think that viewModel code and ui code are needed for understanding. But i left it just in case
I need an unique combination of date and nutrientId, and they don’t have to be primary keys. I tried to add simple key for every row(just an integer id) instead of make nutrientId and date primary keys. But result was the same. Thank you in advance