I'm using data binding, I want to set a text to a TextView via LiveData like this:
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
to set the textview
viewModel.toolbarTitle.postValue(R.string.profile_title_my_documents)
view model implementation
val toolbarTitle = MutableLiveData<@androidx.annotation.StringRes Int>()
and then the xml (removed irrelevant stuff)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<data>
<variable
name="viewModel"
type="packagename.MyViewModel"
/>
</data>
<TextView
android:id="@+id/title"
style="@style/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{viewModel.toolbarTitle}"
/>
</layout>
so basically if I remove the LiveData and use an Int value it works fine, but with LiveData I get an exception:
2020-04-09 14:38:59.929 19744-19744/ E/AndroidRuntime: FATAL EXCEPTION: main
Process: , PID: 19744
java.lang.RuntimeException: Failed to call observer method
at androidx.lifecycle.ClassesInfoCache$MethodReference.invokeCallback(ClassesInfoCache.java:226)
...
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:348)
at android.widget.TextView.setText(TextView.java:5831)
at ToolbarBindingImpl.executeBindings(ToolbarBindingImpl.java:146)
at androidx.databinding.ViewDataBinding.executeBindingsInternal(ViewDataBinding.java:472)
at androidx.databinding.ViewDataBinding.executeBindingsOn(ViewDataBinding.java:486)
at MyBindingImpl.executeBindings(MyBindingImpl.java:151)
at androidx.databinding.ViewDataBinding.executeBindingsInternal(ViewDataBinding.java:472)
at androidx.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:444)
at androidx.databinding.ViewDataBinding$OnStartListener.onStart(ViewDataBinding.java:1685)
at java.lang.reflect.Method.invoke(Native Method)
it crashes most likely because when the screen open the livedata int value is O and it gets sent to the textview and crashes because there is no resId == 0
How to get around this? and second question, is this a good approach to use livedata like this or is it unnecessary?
UPDATE I used this to get around zero values:
android:text='@{viewModel.toolbarTitle == 0 ? "" : context.getString(viewModel.toolbarTitle)}'