'How do I initialize a collection value for a MutableLiveData object?

class Foo : ViewModel() {
   val bars: MutableLiveData<ArrayList<Bar>> = MutableLiveData()
     get() {
       if(field.value == null) {
         field.setValue(ArrayList()) // NullPointerException
       }
     }
}

class FooTest(){
   @Test fun itShouldNotBlowUp() {
     Foo() //nullPointerException

   }

}

I don't understand how to initialize the value of a MutableLiveData object. I've tried to lazily initialize it via the getter and with an init block. Both approaches throw a null pointer when setting the value. bars is not null however.

Here is the stacktrace:

java.lang.NullPointerException
at android.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:58)
at android.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
at android.arch.lifecycle.LiveData.assertMainThread(LiveData.java:434)
at android.arch.lifecycle.LiveData.setValue(LiveData.java:279)
at android.arch.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)
at org.Foo.<init>(Foo.kt:10)
at org.FooTest.ShouldNotBlowUp(FooTest.kt:3)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

How do I initialize the ArrayList and set it as the value of bars?



Solution 1:[1]

The answer to the question is: if you want to give it an empty value clearly, but the variable is not null and you can at least use it without breaking the program.

to create a variable:

val myVariable = MutableLiveData<ArrayList<String>>()

Well, now you only have to pass the constructor of the empty list within the type parentheses so that your variable does not remain with a Null value.

val myVariable = MutableLiveData<ArrayList<String>>(arrayListOf())

I know it's an old question but in case it can help someone, it helped me discover this ;)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jesr2104