How to instantiate ViewModel that extends AndroidViewModel?

此生再无相见时 提交于 2021-01-29 12:28:56

问题


I'm following a tutorial where a ViewModel extends an abstract class in order to use coroutines, this is the class that extends:

abstract class BaseViewModel(application: Application) : AndroidViewModel(application), CoroutineScope {
private val job =  Job()

override val coroutineContext: CoroutineContext
    get() = job + Dispatchers.Main

override fun onCleared() {
    super.onCleared()
    job.cancel()
}}

And this is the ViewModel:

class ViewModel(application: Application) : BaseViewModel(application) {}

So in MainActivity I'm trying to instantiate the class like this:

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    viewModel = ViewModelProvider(this)[ViewModel::class.java]}

In the tutorial the guy perfectly does this but when I try to run the application it throws me an exception:

 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.name.nameapp.main.viewmodel.ViewModel

I feel like I'm missing something can you guys point what it is, if you need more information I'll gladly post it


回答1:


Your ViewModel is child of AndroidViewModel which require an Application object. So you will have to provide the Factory class in order to instantiate the ViewModel. Like so:

val viewModelProvider = ViewModelProvider(
     this, 
     ViewModelProvider.AndroidViewModelFactory(application)
)
viewModel = viewModelProvider[MainViewModel::class.java]

If you are using the fragment library from Jetpack

implementation "androidx.fragment:fragment-ktx:1.2.5"

You can use property delegation like so:

val viewModel: ViewModel by viewModels()


来源:https://stackoverflow.com/questions/65015669/how-to-instantiate-viewmodel-that-extends-androidviewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!