79397284

Date: 2025-01-29 15:40:37
Score: 2
Natty:
Report link

In my case, the reason for

Cannot create an instance of class xx.xx.XXViewModel at androidx.lifecycle.viewmodel.internal.JvmViewModelProviders.createViewModel(JvmViewModelProviders.kt:40)

is that because I don't annotate MainActivity with @AndroidEntryPoint. After annotating it, the error disappear. I am using hilt.

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
}

Here is the reference I find with my problem https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-factories

and the following words help me a lot:

Note: When injecting ViewModels using Hilt as a dependency injection solution, you don't have to define a ViewModel factory manually. Hilt generates a factory that knows how to create all ViewModels annotated with @HiltViewModel for you at compile time. Classes annotated with @AndroidEntryPoint can directly access the Hilt generated factory when calling the regular ViewModel APIs.

Reasons:
  • Blacklisted phrase (1): help me
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @AndroidEntryPoint
  • User mentioned (0): @HiltViewModel
  • User mentioned (0): @AndroidEntryPoint
  • Low reputation (1):
Posted by: Henry Xia