问题
I have two different projects. In the first one I use ViewModel with my activity and Room database. Everything works. Then I just created new project for different purposes and there I instantiate ViewModel absolutely the same way, but my app crashes with this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.MainViewModel
at android.app.ActivityThread.performLaunchActivity(Unknown Source:591)
at android.app.ActivityThread.handleLaunchActivity(Unknown Source:36)
at android.app.servertransaction.LaunchActivityItem.execute(Unknown Source:57)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(Unknown Source:99)
at android.app.servertransaction.TransactionExecutor.execute(Unknown Source:34)
at android.app.ActivityThread$H.handleMessage(Unknown Source:36)
at android.os.Handler.dispatchMessage(Unknown Source:21)
at android.os.Looper.loop(Unknown Source:207)
at android.app.ActivityThread.main(Unknown Source:107)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
at com.android.internal.os.ZygoteInit.main(Unknown Source:274)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.MainViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.kazguiu.MainActivity.applyAdapterAndViewModel(MainActivity.kt:37)
at com.kazguiu.MainActivity.onCreate(MainActivity.kt:25)
at android.app.Activity.performCreate(Unknown Source:16)
at android.app.Activity.performCreate(Unknown Source:1)
at android.app.Instrumentation.callActivityOnCreate(Unknown Source:3)
at android.app.ActivityThread.performLaunchActivity(Unknown Source:368)
at android.app.ActivityThread.handleLaunchActivity(Unknown Source:36)
at android.app.servertransaction.LaunchActivityItem.execute(Unknown Source:57)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(Unknown Source:99)
at android.app.servertransaction.TransactionExecutor.execute(Unknown Source:34)
at android.app.ActivityThread$H.handleMessage(Unknown Source:36)
at android.os.Handler.dispatchMessage(Unknown Source:21)
at android.os.Looper.loop(Unknown Source:207)
at android.app.ActivityThread.main(Unknown Source:107)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(Unknown Source:11)
at com.android.internal.os.ZygoteInit.main(Unknown Source:274)
Caused by: java.lang.InstantiationException: java.lang.Class<com.example.MainViewModel> has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
I instantiate ViewModel in activity like this:
private lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
applyAdapterAndViewModel()
}
private fun applyAdapterAndViewModel() {
mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
}
My ViewModel:
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val exampleDao = Database.getDatabase(application).exampleDao()
private val repository = Repository(exampleDao)
fun getSubjects() = repository.getSubjects()
fun addSubjects(subject: Subjects) = viewModelScope.launch(Dispatchers.IO) {
repository.addSubject(subject)
}
}
This way of using ViewModel is the same as my previous project. Only difference is that I have two additional dependencies in my current gradle:
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
If I delete them, Android Studio doesn't recognize ViewModelProvider, but I don't have these dependencies in my previous projects at all and I use LiveData and ViewModel absolutely the same way(even the imports are the same) there. So, what am I supposed to do?
回答1:
Your ViewModel requires an argument application: Application
which can only be provided by using a ViewModelFactory like so:
ViewModelFactory
class MainViewModelFactory(
private val application: Application
) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
return MainViewModel(application) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
MainActivity
private fun applyAdapterAndViewModel() {
// Not so kotlinic
mainViewModel = ViewModelProvider(this,MainViewModelFactory(application)).get(MainViewModel::class.java)
}
Also, in MainActivity, replace
private lateinit var mainViewModel: MainViewModel
with
private val viewModel by viewModels<MainViewModel> {
MainViewModelFactory(application) }
来源:https://stackoverflow.com/questions/65003812/cannot-create-an-instance-of-class-viewmodel-in-the-new-project