mengmeng
mengmeng

Reputation: 1506

Pass value of a MutableLiveData of ViewModels

I'm very very new to Android and I'm trying to understand/integrate Data Binding.

I think I'm missing something since it always displays null

Here is my ViewModel

class LockDetailsModel: ViewModel() {
    var name = MutableLiveData<String>()

    fun setName(name: String) {
        this.name.value = name
    }

In my LockActivity, I set the value of name based on a certain field.

val viewModel: LockDetailsModel by viewModels()
viewModel.setName(unitName.toString())

And in my other activity, which displays the layout, this is what I did to bind the model

 val viewModel: LockDetailsModel by viewModels()
 binding: ActivityConnectLockBinding = DataBindingUtil.setContentView(this, R.layout.activity_connect_lock)
 binding.lockDetails = viewModel
 binding.lifecycleOwner = this

It displays null :(

Thanks in advance for your help!

Upvotes: 0

Views: 572

Answers (1)

Karunesh Palekar
Karunesh Palekar

Reputation: 2345

The reason behind you getting null value is because you are using different viewModel instances in both the activities , thus the value stored by you in first Activity cannot be obtained in the Second activity . You need to have SharedViewModel between both the activities , which is not possible due to Single Activity principle . So to implement logic that you want to implement you need to have Fragments and make use of fragment-ktx library to easily create SharedViewModel .If you want an example you can refer to my answer here :

Want to show progress bar while moving to the previous page from the current page

The above answer describes how to get progress of a download started in one activity into another .

Upvotes: 1

Related Questions