ViewModelProviders is not working inside my Fragment
Fragments offer a helper method for retrieving a non-null Activity - requireActivity()
. Use that instead of activity
:
viewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)
As an alternative, you can include the fragment-ktx
dependency in your app and use the by activityViewModels() Kotlin property extension instead of using ViewModelProviders.of()
at all:
val viewModel: SharedViewModel by activityViewModels()