1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MediatorLiveDataでNullPointerExceptionが出たときの対処法

Last updated at Posted at 2022-09-15

はじめに

以下のエラーが出た。

at androidx.databinding.ViewDataBinding.updateRegistration(ViewDataBinding.java:653)

ActivityMainBindingImpl.java
if (vModel != null) {
    // read vModel.isNetworkError
    vModelIsNetworkError = vModel.isNetworkError();
}
pdateLiveDataRegistration(0, vModelIsNetworkError); //この行で上記のエラー

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.lifecycle.LiveData.observeForever(androidx.lifecycle.Observer)' on a null object reference

MediatorLiveData.java
void plug() {
    mLiveData.observeForever(this); //この行で上記のエラー
}

書いたコードの概要

viewModelをbindする形でレイアウトを作成。

activity_main.xml
<include
    layout="@layout/view_network_error"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:isNetworkError="@{viewModel.isNetworkError}"
/>
MainViewModel.kt
val isNetworkError = MediatorLiveData<Boolean>().apply {
    addSource(loadingResult) {
        this.value = it == State.ERROR
    }
}

private val resultState = MutableLiveData<State>().apply {
    value = State.SUCCESS 
}

原因と修正

mLiveDataのobserveでぬるぽが出ているためaddSourceの対象であるLiveDataが原因であると推測。

結果として宣言順が問題の原因であったため、以下のようにaddしているLiveDataを先に宣言して修正。

MainViewModel.kt
private val resultState = MutableLiveData<State>().apply {
    value = State.SUCCESS 
}

val isNetworkError = MediatorLiveData<Boolean>().apply {
    addSource(loadingResult) {
        this.value = it == State.ERROR
    }
}

そりゃそうなんですけどね。
宣言順、気をつけましょう🥺

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?