androidviewmodeldagger-hilt

java.lang.RuntimeException: Cannot create an instance of class <package- name>viewmodel.LoginViewModel


i have encountered this issue. i am using jetpack compose with android hilt in my current android project. Application crashes as soon as the activity appears in the screen. After viewing many solution, many suggested to make

 @Composable
    fun NextPage() {
        val navController = rememberNavController()
        val viewModel = hiltViewModel<LoginViewModel>()

        NavHost(navController = navController, startDestination = "signin") {
            composable("signin") { SignInScreen(navController,viewModel) }
     

but it keep crashing after implementing all those points

After viewing many solution, many suggested to make

@AndroidEntryPoint

`val viewModel = hiltViewModel<LoginViewModel>()`


@Composable
    fun NextPage() {
        val navController = rememberNavController()
        val viewModel = hiltViewModel<LoginViewModel>()

        NavHost(navController = navController, startDestination = "signin") {
            composable("signin") { SignInScreen(navController,viewModel) }
     

implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.8.4
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.4
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.8.5
 

but it keep crashing, after implementing all those above mentioned points


Solution

  • I found solution from android google documentation I added one more dependencies in android gradle

    implementation("androidx.hilt:hilt-navigation-compose:1.2.0")
    
    
     @Composable
        fun NextPage() {
            val navController = rememberNavController()
            val viewModel = hiltViewModel<LoginViewModel>()
    
            NavHost(navController = navController, startDestination = "signin") {
                composable("signin") { SignInScreen(navController,viewModel) }
         
    

    and then it worked