ybybyb
ybybyb

Reputation: 1739

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

I'm making an app using the MVVM pattern.

I am implementing a function to add an item to the recycler view when a button is clicked, but I get a NullPointException error from the observer. (To be precise, you press a button to switch screens and add items based on the received argument.)

What went wrong..?

I referenced this

In Fragment

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
    }
}

ERROR

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$4.onChanged(WriteRoutineFragment.kt:66)
        at com.example.writeweight.fragment.WriteRoutineFragment$onViewCreated$4.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)

Upvotes: 0

Views: 1094

Answers (1)

mehul bisht
mehul bisht

Reputation: 742

The issue here is, MutableLiveData<ArrayList<RoutineModel>> is set to just MutableLiveData(), try changing it to MutableLiveData(arrayListOf()) it should work :)

EDIT:

The reason is simple, the ArrayList requires to be initialised even inside the MutableLiveData wrapper around it.

Upvotes: 3

Related Questions