It really depends on how do you create your ViewModel
instance. Now you are creating ViewModel
by its constructor, but that is not a proper way. You should use ViewModelProvider
or extension methods that were created by Google team.
If you go with ViewModelProvider
you should do it like this:
TimeTableViewModel viewModel = new ViewModelProvider(this).get(TimeTableViewModel.class);
It is important to pass the correct context to ViewModelProvider
constructor call. If you are in fragment and you will just use getContext()
instead of getActivity()
, you will not get the same instance as it was created in Activity. You will create a new instance of ViewModel
, that will be scoped only inside of fragment lifecycle. So it is important to use in both parts activity context to get the same instance.
Activity part:
TimeTableViewModel viewModel = new ViewModelProvider(this).get(TimeTableViewModel.class);
Fragment part:
TimeTableViewModel viewModel = new ViewModelProvider(getActivity()).get(TimeTableViewModel.class);
Is important that your fragment is located inside the same activity that is using this ViewModel
.
But guys at Google has make it easier for us with some extension methods. But as far as I know, they are working only in Kotlin classes. So if you have Kotlin code, you can declare your ViewModel
simply like this:
private val quizViewModel: TimeTableViewModel by activityViewModels()
For Fragment scoped ViewModel
you need to write something like this:
private val quizViewModel: TimeTableViewModel by viewModels()
But you have to add Kotlin ktx dependency to your project build.gradle
file. For example like this:
implementation 'androidx.fragment:fragment-ktx:1.1.0'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…