Search code examples
androiddatabasekotlinkeylet

am i understanding ?.let wrong? (PrimaryKey error when either updating or inserting into room db)


this function below

in goes the dictWord if it exists it increases the amount property by one updates in the db and returns out of the uiscope - out of the function and when the getDictWord return a null it goes to creation a newDictWord and adds that into the db and leaves the coroutine scope and then the function no?

because i do get " android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: DictWord.name (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY)" from time to time from that

   fun addOrIncreaseDictWordAmount(dictWord: String) {
        uiScope.launch {
            userDatabaseDao.getDictWord(dictWord)?.let {
                it.amount += 1
                userDatabaseDao.updateDictWord(it)
                return@launch
            }
            // adds the strain to the AddNew dropDown list
            val newDictWord = DictWord(name = dictWord)
            userDatabaseDao.insertDictWord(newDictWord)
        }

Solution

  • In regards to your initial question regarding the ?.let syntax...

    This syntax will work with a nullable value (in your case the return of getDictWord(dictWord). If that value is not null you will be passed into the attached block, and the value will be passed into the block as it, and guaranteed not-null for the rest of the closure. If the value is null, it will skip that closure completely.

    As for the intermittent error you are receiving, and based on your provided information, I am thinking your solution to that would be involved with the answer given here: UNIQUE constraint failed

    If you are able to provide more involved logs and information I would be happy to edit and improve this answer to get your issue fixed.