nikhil bansal
nikhil bansal

Reputation: 451

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.

Upvotes: 2

Views: 6127

Answers (2)

Arka Prava Basu
Arka Prava Basu

Reputation: 2560

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
    }

Upvotes: 4

Philio
Philio

Reputation: 4185

From your activity you can use:

Kotlin:

applicationContext

Java:

getApplication().getApplicationContext()

Upvotes: 0

Related Questions