androidkotlinandroid-architecture-navigationup-navigation

Handling up button in Android navigation component


I have two fragments A & B inside a main activity set up with the Android Navigation Component. Fragment A contains a recyclerView in which an item click will navigate to Fragment B.

The issue is when I click the up button inside Fragment B, it will not navigate back to Fragment A but will reload Fragment B instead. It will only navigate back on a second click. Same behaviour with the back button.

Once I manage to navigate back to Fragment A, when I click on an item to go to Fragment B, i get this exception thrown :

java.lang.IllegalArgumentException: navigation destination com.example.sampleapp:id/action_accountSelectionFragment_to_cameraSelectionFragment is unknown to this NavController

Is this a known bug of the latest versions ? I'm on 2.2.0-alpha01

Here is how I've implemented navigation :

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val navController = findNavController(R.id.nav_host_fragment)
        setupActionBarWithNavController(navController)
    }

override fun onSupportNavigateUp() = 
    findNavController(R.id.nav_host_fragment).navigateUp()

FragmentA : the callback method that is called when I click on an item in my recyclerView

private fun goToCameraSelectionActivity(accountId: Int, accountName: String) {
        findNavController().navigate(
            AccountSelectionFragmentDirections.actionAccountSelectionFragmentToCameraSelectionFragment(accountName, accountId)
        )
}

I have tried playing with 'popTo' but the problem remains the same.


Solution

  • Problem was fixed after I called

    findNavController().navigate(
        AccountSelectionFragmentDirections.actionAccountSelectionFragmentToCameraSelectionFragment(accountName, accountId)
    )
    

    in my adapter onClickListener instead on after going through the loop of my MVI architecture (click -> intent -> state -> navigate ).

    There seems to be a timing issue with the component.