Search code examples
androidmvvmviewmodelandroid-jetpackandroid-viewmodel

Get ViewModel ViewModelProvider.Factory and Application Context


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.


Solution

  • You would need an Application in ViewModel.Factory to instantiate an AndroidViewModel.

    Ways to achieve this

    • if you are instantiating the ViewModel in your Activity/Fragment then do 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()
    
    • if your app has an 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
        }