3

I have my Activity MainActivity.kt .

And and one ViewModel MainActivityViewModel.kt

And I want to observe my live data to my 3 different fragments.

class MainActivity{
      
      lateinit var mainActivityViewModel: MainActivityViewModel
      ...

     mainActivityViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainActivityViewModel::class.java)
}

class MainFragmentOne{
      
      lateinit var mainActivityViewModel: MainActivityViewModel
      ...

     mainActivityViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainActivityViewModel::class.java)
}

But my observer only work on activity not on the fragments.

peterh
  • 11,875
  • 18
  • 85
  • 108
Hello world
  • 80
  • 1
  • 10

4 Answers4

2

Hey there you are doing everything greate except one thing you should use requireActivity() instead on this in your fragment class.

Make sure your all fragment are attached to your viewModel holding Activity.

class MainActivity{

      lateinit var mainActivityViewModel: MainActivityViewModel
      ...

     mainActivityViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainActivityViewModel::class.java)
}

class MainFragmentOne{

      lateinit var mainActivityViewModel: MainActivityViewModel
      ...

     mainActivityViewModel = ViewModelProviders.of(requireActivity(), viewModelFactory).get(MainActivityViewModel::class.java)
}

This will help you solve your issue.

For further detail view this.

Arbaz Pirwani
  • 935
  • 7
  • 22
1

The ViewModelProviders.of has 2 different constructors:

of(Fragment fragment, ViewModelProvider.Factory factory)

Creates a ViewModelProvider, which retains ViewModels while a scope of given fragment is alive.

of(FragmentActivity activity, ViewModelProvider.Factory factory)

Creates a ViewModelProvider, which retains ViewModels while a scope of given Activity is alive.

Basically when you used this as the first parameter in your activity, you passed the context of the activity and created a viewmodel that will be alive in the scope of the activity, however your second this is the context to your fragment, meaning that the second ViewModel will be alive as long as your fragment is alive (only one fragment).

What instead you should be doing in your fragment is using the context of the activity, since activity is always alive when fragments are attached and swapped. You should change your fragments to:

class MainFragmentOne{

      lateinit var mainActivityViewModel: MainActivityViewModel
      ...

     mainActivityViewModel = ViewModelProviders.of(activity!!, viewModelFactory).get(MainActivityViewModel::class.java)
}

or you can use the requireActivity() method that was the previous answer.

Daniel
  • 2,320
  • 1
  • 14
  • 27
1

To achieve what you are trying to do, you need three things. An activity/fragment that will post the value to the ViewModel, a ViewModel, and an activity/fragment that will retrieve the data from the ViewModel. Lets say your data is stored in an ArrayList, and you want to update and retrieve it from different fragments.
First, we have to implement a ViewModel. It contains the data you want to share between your activities/fragments. You declare the MutableLiveData as an ArrayList then initialize it.

class testviewmodel : ViewModel() {
    val list: MutableLiveData<ArrayList<String>> = MutableLiveData()
    init {
        list.value = arrayListOf()
    }
}

Our next step is to access and update the ArrayList using your activity:

    val viewmodel = ViewModelProviders.of(this).get(testviewmodel::class.java)
    // update the array in Viewmodel
    viewmodel.list.postValue(yourarray)

If you are using a Fragment to update it, use this:

    activity?.let {
        val viewmodel = ViewModelProviders.of(it).get(testviewmodel::class.java)
         // update the array in Viewmodel
        viewmodel.list.postValue(yourarray)
    }

Finally, to retrieve the data from the ViewModel in a fragment, put this inside your onViewCreated:

activity?.let {
    val viewmodel = ViewModelProviders.of(it).get(Dbviewmodel::class.java)
    observeInput(viewmodel)
}

Put this outside of your onViewCreated:

private fun observeInput(viewmodel: testviewmodel ) {

    viewmodel.list.observe(viewLifecycleOwner, Observer {
        it?.let {
            if (it.size > 5) {
                pos = it[5]
//grab it
                Toast.makeText(context,pos,Toast.LENGTH_LONG).show()
//display grabbed data
            }
        }
    })
}

Take a look at this docs for more information about ViewModels
Good Luck! I hope this helps :)

CoderUni
  • 5,474
  • 7
  • 26
  • 58
0

That's because you are using the fragment 'this' instance, and not the activity.

Replace

mainActivityViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainActivityViewModel::class.java)

With

activity?.let { mainActivityViewModel = ViewModelProviders.of(it, viewModelFactory).get(MainActivityViewModel::class.java) }