• Home
  • Cannot create an instance of class viewmodel kotlin – Android

Cannot create an instance of class viewmodel kotlin – Android

If you are trying to create an instance of a ViewModel in your Kotlin code and you are getting an error saying “cannot create an instance of class ViewModel”, it could be because you are trying to create an instance of the ViewModel class directly, which is not possible.

To use a ViewModel in your Android app, you need to use the Android ViewModel library. This library provides a ViewModelProvider class that you can use to create an instance of a ViewModel class.

Here is an example of how you can create an instance of a ViewModel class in Kotlin:

class MyActivity: AppCompatActivity() {

private lateinit var viewModel: MyViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
}
}

In this example, MyViewModel is a class that extends the Android ViewModel class and is responsible for storing and managing UI-related data in the activity.

To create an instance of MyViewModel, you can use the ViewModelProvider class and pass it the Activity or Fragment instance as a parameter. Then, you can call the get() method on the ViewModelProvider object and pass it the MyViewModel class as a parameter to create an instance of the MyViewModel class.

I hope this helps! Let me know if you have any more questions.