您好,我正在尝试使用 Hilt 注入视图模型,但出现以下错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wordssample, PID: 25250
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.wordssample/com.example.wordssample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.wordssample.MainViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.wordssample.MainViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.hilt.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:74)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:69)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
这是我的主要活动:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val viewModel by viewModels<MainViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
....
这是我试图注入的 ViewModel 类
class MainViewModel @ViewModelInject constructor(
@ApplicationContext application: Context,
@Assisted private val savedStateHandle: SavedStateHandle
) : ViewModel() {
private val repositorio = WordRepositorio(application)
val allWords = repositorio.mAllWords
...
感谢您的帮助!谢谢