Home > Enterprise >  Why it says "Cannot create an instance of class com.app.myapp.viewModel" in android jetpac
Why it says "Cannot create an instance of class com.app.myapp.viewModel" in android jetpac

Time:04-17

I am new in adroid , so I have a simple project, when I build project it is throw an error for

 myViewModel = ViewModelProvider(this)[MyViewModel::class.java]

as a "Cannot create an instance of class com.app.myapp.viewModel", I do not know what I missed?

  class Register : ComponentActivity() {

    private lateinit var  myViewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        
       
        myViewModel = [ViewModelProvider(this)::class.java]

        setContent {
            RegisterScreen(myViewModel)
        }
    }
}

@Composable
fun RegisterScreen(
    myViewModel: MyViewModel
  ) {

}

CodePudding user response:

You should create your ViewModel class extending from the ViewModel, something like RegisterViewModel.

Take a look at the documentation for more info: https://developer.android.com/topic/libraries/architecture/viewmodel

CodePudding user response:

You are trying to create a view model from the base class ViewModel. it doesn't work like this

You need to create your own viewmodel class and extend it from the base class ViewModel like this

class MyViewModel : ViewModel() {
    
}

So your code will be like

class MyViewModel : ViewModel() {
    // your implementation
}

class Register : ComponentActivity() {

private lateinit var  viewModel: MyViewModel // changes to this line

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    
   
    viewModel = ViewModelProvider(this)[MyViewModel::class.java] // changes to this line

    setContent {
        RegisterScreen(viewModel)
    }
}

}

BUT if you are using compose you should look at the integration between viewmodel and compose

to make your composable use the viewModel without you creating it then passing it to the composable

@Composable
fun MyExample(
    viewModel: MyViewModel = viewModel()
) {
    // use viewModel here
}
  • Related