Back to last fragment error since no addToBackStack Kotlin

24 views Asked by At

sorry for my bad english

I just update my gradle version and all my navigation become buggy, but I still not sure that this is the reason my navigation become buggy.

this is my fragment handler on MainActivity

val navView: BottomNavigationView = findViewById(R.id.bottom_nav_view)
        val navController = findNavController(R.id.nav_host_fragment)
        navController.setGraph(R.navigation.nav_graph)
        navView.setupWithNavController(navController)

first fragment is HomeFragment that filled in the MainActivity

and if I want to change to another fragment, I'm using this

private fun callFeatureIncome() {
        val fragment = IncomeFragment.newInstance()
        val transaction = fragmentManager?.beginTransaction()
        transaction?.setReorderingAllowed(true)
        transaction?.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        transaction?.replace(R.id.nav_host_fragment, fragment)
        transaction?.addToBackStack(null)
        transaction?.commit()
    }

then error comes, I can't open the IncomeFragment

but if I remove transaction?.addToBackStack(null)

I can go to IncomeFragment

the error is gone, but I can't use back button to back to previous fragment since is not recorder on the stack.

before, all is okay

1

There are 1 answers

0
Heru Prayogo On

answer from @ianhanniballake it happens because I'm using FragmentTransaction on top of NavController.

Now I remove the FragmentTransaction and use this to navigate through the nav_graph

    val bundle = Bundle()
    bundle.putString("bundle_name", contributionId.toString())
    val navHostFragment = activity?.supportFragmentManager?.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    val navController = navHostFragment.navController
    navController.navigate(R.id.your_fragment_id, bundle)