Home > Enterprise >  why it throw an error for NavController as a NullPointerException in jetpack compose?
why it throw an error for NavController as a NullPointerException in jetpack compose?

Time:04-19

I try to learning jetpack compose in android, so I want to use navController in a simple project, when I debug the project it throw an error as a

NullPointerException when trying to get NavController

for in this onClick = {navController.navigate("screenB")} line of code. I do not know what I missed in this project?. I was search on internet to solve it, but I am still not get it.

  @AndroidEntryPoint
  class NavActivity : ComponentActivity() {
    private lateinit var  viewModel: MyViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = ViewModelProvider(this)[MyViewModel::class.java]
        setContent {
            NavScreen()
        }
    }
}

@Composable
fun NavScreen() {
    val viewModel = hiltViewModel<MyViewModel>()
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = "screenA") {

        composable(route = "screenA") {
            ScreenA(navController)
        }
        composable(route = "screenB") {
            ScreenB(navController)
        }
      



    }
}

ScreenA:

@AndroidEntryPoint
class ScreenA : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
      
        setContent {
            val navController = rememberNavController()

            ScreenA(navController)
        }
    }
}

@Composable
fun ScreenA(
    navController: NavController
) {
     Button(
            modifier = Modifier
                .width(30.dp)
                .height(15.dp),

            onClick = {
                navController.navigate("screenB")

            },
            colors = ButtonDefaults.buttonColors(
                backgroundColor = Color.Red
            ),
            shape = RoundedCornerShape(20)
        ) {
            Text(
                text = "OK",
              
            )
      }}

ScreenB:

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ScreenB(
    navController: NavController
) {

}

CodePudding user response:

ScreenA should be composable not Activity. Try to leave only composable component in ScreenA

@Composable
fun ScreenA(
  navController: NavController
) {
 Button(
        modifier = Modifier
            .width(30.dp)
            .height(15.dp),

        onClick = {
            navController.navigate("screenB")

        },
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Red
        ),
        shape = RoundedCornerShape(20)
    ) {
        Text(
            text = "OK",
          
        )
  }}
  • Related