how to instantiate ViewModel In AndroidX?

Updated answer:

Things changed a little bit, as the previously needed dependency – ViewModelProviders – got deprecated (see the old answer for details). You can now use the ViewModelProvider constructor directly.

So, in this case, the answer would be:

private val viewModel = ViewModelProvider(this).get(SheduleViewModel::class.java)

Note that, however, if you include the androidx.activity:activity-ktx:$Version dependency (a few of the commonly used AndroidX dependencies already include it for you), you can make use of property delegation:

private val viewModel: SheduleViewModel by viewModels()

Which internally will use ViewModelProvider and scope your ViewModel to your Activity. It’s just a more concise way of writing the same thing. You can do the same for a Fragment by including the androidx.fragment:fragment-ktx:$Version dependency instead (again, commonly already included by other AndroidX dependencies).

Both the ViewModelProvider constructor and by viewModels() also accept a factory as a parameter (useful for injecting your ViewModel):

private val viewModel = 
    ViewModelProvider(this, viewModelFactory).get(SheduleViewModel::class.java)

and

private val viewModel: SheduleViewModel by viewModels { viewModelFactory }

Use the one that best suits you.

Old answer:

Add the androidx.lifecycle:lifecycle-extensions:$lifecycleExtensionsVersion dependency in order to import ViewModelProviders.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)