ViewModel 的 observe() 方法没有正确观察

ViewModel's observe() method doesn't observe properly

我正在使用 MVVM pattern.

制作应用

我正在实现一个函数,在单击按钮时将项目添加到 recycler view,但我从观察者那里收到 NullPointException 错误。 (准确的说,你按一个按钮切换屏幕,并根据收到的参数添加项目。)

出了什么问题..?

我引用了 this

片段中

override fun onViewCreated(view: View, savedInstanceState
: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        args.workout?.let {
            viewModel.addItem()
        }

        viewModel.item.observe(viewLifecycleOwner) { newItem ->
            adapter.setItems(newItem) // error
        }
    }

ViewModel

class WriteRoutineViewModel : ViewModel() {
    private var _item: MutableLiveData<ArrayList<RoutineModel>> = MutableLiveData()
    val item: LiveData<ArrayList<RoutineModel>> = _item

    fun addItem() {
        _item.value?.add(RoutineModel("test", "ABC"))
        _item.value = _item.value
    }
}

错误

2021-07-15 04:26:25.961 13731-13731/com.example.writeweight E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.writeweight, PID: 13731
    java.lang.NullPointerException: newItem must not be null
        at com.example.writeweight.fragment.WriteRoutineFragment$onViewCreated.onChanged(WriteRoutineFragment.kt:66)
        at com.example.writeweight.fragment.WriteRoutineFragment$onViewCreated.onChanged(WriteRoutineFragment.kt:18)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:133)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:146)
        at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:468)
        at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:425)
        at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:354)
        at androidx.lifecycle.LifecycleRegistry.forwardPass(LifecycleRegistry.java:265)

这里的问题是,MutableLiveData<ArrayList<RoutineModel>> 设置为 MutableLiveData(),尝试将其更改为 MutableLiveData(arrayListOf()) 它应该可以工作:)

编辑:

原因很简单,ArrayList 即使在 MutableLiveData 包装器内部也需要初始化。