kotlinandroid-jetpack-composeandroid-room

App crash after delete item in detail screen and then navigate back to list screen


In DetailViewModel I have this function

fun delete(id: Int) {
  viewModelScope.launch {
    repository.delete(
       Item(
          id = id,
          name = state.name,
       )
    )
 }
}

After I click on Delete button in DetailScreen, the app crash. The delete was successful though.

Here the code in DetailScreen

FilledTonalButton(
  onClick = {
     viewModel.delete(id)
     navigateBack() //navigate to the list screen
  },               
)

The strange think is that if I put the same code in the ListViewModel works fine. I click on a item in the list, and this is deleted and the LazyColumn is updated (the deleted item there is no more)

fun delete(item: Item) {
      viewModelScope.launch {
        repository.delete(
           item
        )
     }
}

And ListScreen code

ElevatedCard (
  elevation = CardDefaults.cardElevation(
    defaultElevation = dimensionResource(id = R.dimen.dimen_8dp)
  ),
  modifier = Modifier           
      .clickable {
         listViewModel.delete(item)
      }
)

The error is

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.utils.deutsch.data.room.Item.getName()' on a null object reference

The method getName() is called into protected void bind method autogenerate by Room.

EDIT

I found the problem. In my init function in the DetailViewModel I have a Flow that tries to get Item every time that there is a modification in the database, but in case of delete item, the item is null. I modified my init function like this:

init {
        if(id!= -1){
            viewModelScope.launch {
                repository.getItem(id).collectLatest {
                    if(it != null){ //I added this check
                        state = state.copy(
                            nameIt = it.name
                        )
                    }
                }
            }
        }
    }

Solution

  • I found the problem. In my init function in the DetailViewModel I have a Flow that tries to get Item every time that there is a modification in the database, but in case of delete item, the item is null. I modified my init function like this:

    init {
            if(id!= -1){
                viewModelScope.launch {
                    repository.getItem(id).collectLatest {
                        if(it != null){ //I added this check
                            state = state.copy(
                                nameIt = it.name
                            )
                        }
                    }
                }
            }
        }