android – As ViewModelProviders.of() is deprecated, How should i create object of ViewModel?-ThrowExceptions

Exception or error:

I have been trying to create an Object of ViewModel in an Activity but ViewModelProviders is deprecated So what’s the alternative to create the ViewModel’s object.

How to solve:

Simply replace:


boardViewModel = ViewModelProviders.of(this).get(

With this:

boardViewModel = ViewModelProvider(this).get(


ViewModelProviders.of() has been deprecated. You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality. (aosp/1009889)

Please click here to see the solution


The simple option for the next several months is to stick with stable or beta versions. ViewModelProviders is only deprecated starting with 2.2.0, presently in an alpha03 release.

For when you do move to 2.2.0 or higher of the lifecycle dependencies, your options depend on your language:

  • If you are using Java, use the ViewModelProvider() constructor, passing in your activity or fragment

  • If you are using Kotlin, there is supposed to be a by viewModels() property delegate, though I am not finding it in the source code…


If you’re using Kotlin, instead of:

private lateinit var viewModel: EntityGridViewModel


// Deprecated
viewModel = ViewModelProviders.of(this).get(

You can use the nicer:

private val viewModel: EntityGridViewModel by viewModels()


ViewModelProviders.of() has been deprecated.
enter image description here

Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.

 mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);


this worked for me:
An outline of the steps that created the problem for me

This Gradle upgrade created the problem for me.


implementation 'androidx.core:core:1.1.0'


implementation 'androidx.core:core:1.2.0'

IN MAIN ACTIVITY Java/Kotlin Files

This import Statement

import androidx.lifecycle.ViewModelProviders

had to be changed to

import androidx.lifecycle.ViewModelProvider

This KOTLIN viewModel statement

viewModel = ViewModelProviders.of(this).get(

had to be changed to

viewModel = ViewModelProvider(this).get('

and in JAVA

This line of JAVA code

mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);

had to be changed to

mViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);'

and then it all worked for me.

Leave a Reply

Your email address will not be published. Required fields are marked *