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.