我不能在数据绑定上使用livedata



我试图在xml中达到我的livedata值,但我得到了这个错误"java.lang.RuntimeException:未能调用observer方法">";由以下原因引起:java.lang.NullPointerException:试图对null对象引用调用虚拟方法"int java.lang.String.length((">

Xml文件

<data>
<variable
name="detailViewModel"
type="com.kseyko.satellite.ui.view.detail.DetailViewModel" />
</data>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".ui.view.detail.DetailFragment">

<TextView
android:id="@+id/textViewDetailFirstFlight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="60dp"
android:gravity="center"

android:text="{detailViewModel.formatDate(detailViewModel.sattelliteLiveData.first_flight(}"/>

viewHolder

类DetailViewModel(私有val卫星存储库:卫星存储库(:BaseViewModel(({

private val _satelliteLiveData = MutableLiveData<Satellite>()
var satelliteLiveData: LiveData<Satellite> = _satelliteLiveData
fun fetchSatellite(satellitePosition: Int) {
viewModelScope.launch {
val satelliteLive = withContext(Dispatchers.IO) {
satelliteRepository.getSatellite(satellitePosition)
}
_satelliteLiveData.value = satelliteLive
}
}
fun formatDate(firstFlight: String?): String {
var formatter = SimpleDateFormat("yyyy-MM-dd")
val date = formatter.parse(firstFlight)
formatter = SimpleDateFormat("dd.MM.yyyy")
return formatter.format(date)
}

}

谢谢

您在哪里调用fetchSatellite方法?空指针异常表示您尚未设置_satelliteLiveData的数据。创建init { }块,然后将_satelliteLiveData放入其中以获取数据

最新更新