I am extending AndroidViewModel to get an application context in my ViewModel but Now I also want to pass some parameters to my ViewModel. After some google search, I came to know that I can use ViewModelProvider.Factory to get Parametrized constructor of my MyViewModel but how to get an application context.
Thanks in advance.
You would need an Application
in ViewModel.Factory
to instantiate an AndroidViewModel
.
Ways to achieve this
getApplicationContext()
and cast it as Application
. If in fragment you can get the hosting Activity and get Application from it.// Kotlin code
viewModel = ViewModelProviders.of(this,
ViewModel.Factory(activity?.application!!, param1, param2)) // from an fragment onViewCreated()
Application
class expose an method to get an application instance.// JAVA code
public static Application getApp() {
return YourApplication.instance; // instance will be an static field in Application class
}