'Cannot create an instance of class ViewModel with constructor

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?



Solution 1:[1]

If you using Dagger-hilt may b you can't add @HiltViewModel. also check in your activity whether this tag (@AndroidEntryPoint) is added or not.

Solution 2:[2]

Do you mean classic getElementsByTagName() in javascript? You can indeed get elements like that and apply custom logic in your ts that will handle their template display. If you mean exactly something like <mat-icon>refresh</mat-icon>, then you'd need to make your own libraries or plugins. Much easier and closest to that, though, is to define your own components that will have selector you need and handle all the content and attributes as you like, for example: <your-selector [icon]="thatSillyIconWithAnElephant"></your-selector> and then with @Input grab the value and handle it in ts.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2