op_man
op_man

Reputation: 35

Using same viewmodel on different fragments

I have viewModel on Fragment A, which I load in this way:

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

then from fragment A, I go to fragment B. Is this possible to use the same viewmodel on fragment B? In Fragment B I tried (as in docs):

private val viewModel: AFragmentVM by activityViewModels()

but I get an exception while trying to use this ViewModel:

java.lang.RuntimeException: Cannot create an instance of class ...AFragmentVM
...
BFragment.getViewModel(Unknown Source:2)
BFragment.onCreateView(ChartFragment.kt:40)
...
Caused by: java.lang.NoSuchMethodException: ...AFragmentVM.<init> [class android.app.Application]

EDIT:

Based on @SebastienRieu and @IntelliJ Amiya answers, everything that I had to do was to create ViewModel on Fragment A in this way:

viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)

Or:

viewModel  = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)

Then on Fragment B I could use:

private val viewModel: AFragmentVM by activityViewModels()

Upvotes: 1

Views: 1674

Answers (2)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75788

Fragment A

viewModel  = ViewModelProvider(let {activity}!!,viewModelFactory).get(AFragmentVM::class.java)

Fragment B

 private lateinit var viewModel: AFragmentVM 

Upvotes: 1

SebastienRieu
SebastienRieu

Reputation: 1512

If the two fragments are in the same activity you should replace this :

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

by this

viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(AFragmentVM::class.java)

and add a viewModel in the activity and initialize it in this activity like this :

viewModel = ViewModelProvider(this, viewModelFactory).get(AFragmentVM::class.java)

With requireActivity() when setup the VM in fragment you tell the fragment to use the activity shared ViewModel

Upvotes: 3

Related Questions