Hi guys, How can the second sentence produce a Nu...
# announcements
k
Hi guys, How can the second sentence produce a NullPointerException?
Copy code
lateinit var aLiveData: LiveData<List<..>>
val list = aLiveData.value
The crashlytics said there is a NPE in the second line. It occurs occasionally. I dont really get why, I thought it could be about the lateinit so I change it to a nullable variable (despite the fact there is no "lateinit exception"). Is that correct?
a
I think you want to use
val list get() = aLiveData.value
Accessing variable which isn't initialized is not permissible, you'll get PropertyNotInitializedException, though don't know how you got the NPE instead.
k
thank you, but why can't I define
val list = someLiveData.value
directly?
a
It creates a field and initialize it to
someLiveData.value
which doesn't exist at the time of creating variable
list
val list get() = aLiveData.value
is basically like a function and doesn't have any field in it, you can think of it as
fun getList(): List<...> = someLiveData.value
k
I think the full version shoud be
val list: <DataTye>
get () =...
so backing properties in kotlin is something like you create a not null list and initialize it to a value?
I changed it like this:
var aLiveData: LiveData<List<T>>? = null
then
val list = aLiveData?.value
shoud be no prob now?
a
list won't be changed when livedata changes, it'll always be null.
it "stores" the result at the time it is initialized
🤔 1
k
I mean
var aLiveData: LiveData<List<T>>? = null
aLiveData = getDataFromDb()
val list = aLiveData?.value
a
I don't know how does that work, are you declaring property in a class or a variable in a function?
Before seems like in a class, but now in a method as you are calling a function in the next line
k
😂 sorry that 3 sentences are in 3 different positions in my ViewModel. It works now btw thank you very much for your help. I just can't know why it is NPE. Sadly that I can't reproduce the bug
a
blob thinking upside down