Search code examples
kotlinandroid-room

Problem with autogenerate id ROOM Database


I want to add single match to specif tournament by tournament id Everything is working correctly apart from tournament.id in generateMatchesFFA() is always 0.

I think the reason of this problem is because an id in Tournament data class is set to autogenerate=true. How i should set correct tournament id to SingleMatch data

My try: It's a ViewModel file. I invokes addTournament function when user click "Add Tournament".

fun addTournament(tournament: Tournament) {
    viewModelScope.launch(Dispatchers.IO) {
        repository.insertTournament(tournament)
        generateMatchesFFA(tournament)
    }
}

private suspend fun generateMatchesFFA(tournament: Tournament) {

    val listOfPlayers = tournament.players
        .trim('[', ']')
        .split(", ")
        .map {
            it.trim('"')
        }

    val size = listOfPlayers.size

    for (i in 0 until size) {
        for (j in i+1 until size) {
            singleMatchRepository.insertMatch(SingleMatch(
                player1 = listOfPlayers[i],
                player2 = listOfPlayers[j],
                tournamentId = tournament.id
            ))
        }
    }
}

I also leave link to github project: https://github.com/DawidSiudeja/Tournament/tree/master/app/src/main/java/com/example/tournamentapp


Solution

  • Autogenerate has nothing to do with it. (Side note, you might want to look up what it means because the name is super misleading and in most cases it should be turned off. IDs are still automatically generated when it’s turned off—they just won’t be guaranteed not to be a number that once belonged to a row that has been deleted.)

    From browsing your code, I see that the Tournament you pass to this function has the default ID of 0, which means SQLite will generate an ID for it when the item is inserted in the database. That’s fine, but then you never do anything to retrieve that generated ID. You just keep using the original Tournament instance that has id 0.

    If you want to easily retrieve the ID of a row that was just inserted, change your DAO insert function to have a return type of Long. That returned Long is the ID of the row that was inserted.