Home > Enterprise >  Cannot create an instance of class ViewModel with constructor
Cannot create an instance of class ViewModel with constructor

Time:10-21

I'm trying to use the viewmodel in my activity but my app crashes the error "Cannot create an instance of class" from the viewmodel. The ViewModel is like this:

class MyViewModel@Inject constructor(val application: Application) : ViewModel() {
   //...
}

In my activity, I have this:

class Activity: BaseActivity(){
       val viewModel: MyViewModel by viewModels()

       override fun onCreate(savedInstanceState: Bundle?) {
                 super.onCreate(savedInstanceState)
       }
}

If I delete the constructor, my app works but I need to get packageName, so I need context or application.

Why I'm getting this error? Any idea?

CodePudding user response:

You can use AndroidViewModel

class MyViewModel@Inject constructor(val application: Application) : AndroidViewModel(application)
  • Related