Tag Archives: Observation state

Android room and java.lang.nullpointerexception and observeasstate

val itemList: List<Message>?by messageViewModel.messageList.observeAsState()

MessageWindow(itemList = itemList!!)

The error of null pointer is caused by the problem of observeasstate function,

There are two versions of the obserasstate function. One is to give an initial value, and the other is to give no initial value, that is, the version I reported an error.

Because there is no initial value, it will return null!

 

  Because my itemlist starts the background thread to query in the ViewModel, and the main thread runs faster than the background thread, when the main thread runs to the observer line, the data is not ready, the result returns null, and the result conflicts with the following line.

 

The solution is to use another version of the obser function to give an initial value so that a null error will not be reported.

val itemList: List<Message>?by messageViewModel.messageList.observeAsState(listOf())