Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Databinding TextView no data when use apply function to assign lifeCycleOwner

The TextView cannot display my data which fetch from network. I am sure that I assign the lifecycleOwner and viewModel in onCreateView but nothing displayed. Then I remove apply function and assign lifecycleOwner line by line and it works but I don’t know why. Please tell me if anyone know the reason!

In ViewModel, I have a data class for display

private val _priceData = MutableLiveData<PriceData>()
val priceData: LiveData<PriceData>
    get() = _priceData

In Fragment, I assigned the lifecycleOwner and viewModel in onCreateView

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    // The TextView display nothing using apply
    binding = FragmentPriceBinding.inflate(inflater, container, false).apply{
        lifecycleOwner = viewLifecycleOwner
        viewModel = viewModel
    }

    // The TextView show the data correctly if I assign lifeCycle line by line
    binding = FragmentPriceBinding.inflate(inflater, container, false)
    binding.lifecycleOwner = viewLifecycleOwner
    binding.viewModel = viewModel

    return binding.root
}

Then I use dataBinding in xml TextView to observe liveData

<data>
        <variable
            name="viewModel"
            type="com.yuyu.gasprice.price.PriceViewModel" />
</data>
<TextView
       android:id="@+id/gasoline_change"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:text="@{viewModel.priceData.predict}" />

>Solution :

You assign your binding.viewModel by binding.getViewModel() . I think you want to assign the viewModel which init from fragment right?

You should replace

viewModel = viewModel

with

viewModel = this@YourFragment.viewModel
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading