https://kotlinlang.org logo
Title
j

John Aoussou

11/12/2021, 11:38 AM
Does any one know the proper way to access the LiveData that you get from a room database in compose? I'm sure the DB is not empty, because when I do the following the correct entry is printed:
val items = viewModel.readAllData.observeAsState()
val TAG = "check"
val item1 = items.value?.get(0)?.original
Log.i(TAG,item1.toString())
However, if I try to show the text in a Text element like so
Column{
    Text(text = item1!!)
}
it tells me the List is empty ¯\_(ツ)_/¯
c

Csaba Kozák

11/12/2021, 12:55 PM
!!
you have an unsafe operator here. You should check if it is not null (and empty), and display it in that case.
val items by viewModel.readAllData.observeAsState()

if (!items.isNullOrEmpty()) {
  Text(text = items!!.first()) // safe to call here
}
j

John Aoussou

11/12/2021, 1:14 PM
@Csaba Kozák Thank you. I did think of doing that, but I thought it was bad practice in Kotlin to check for nullity manually? Also, why does it work in the Log? (if it's a long explanation please don't bother).
c

Csaba Kozák

11/12/2021, 1:29 PM
In the first snippet, you are using a safe-call operator
?.
, so event when it is null first, you should see itt logging
null
, but no crash.
Well, you can call it manual null check, but in the end, it generates the same code. Instead of the
if
, you could also use
items?.let {
if you want.
🙇‍♂️ 1