androidkotlinandroid-architecture-navigation

Navigation component Kotlin - cannot be found from the current destination


I have a fragment A,B,C. Its okay when navigating from A -> B, but from B -> C it crashes.

Here is my Navigation

enter image description here

Here is my navigation code

 categoryProductItemListAdapter.setOnItemClickListener {
        val action = CategoryProductItemsDirections.actionCategoryProductItems2ToProductItem(null, it)
        navController = Navigation.findNavController(requireView())
        navController?.navigateUp()
        navController?.navigate(action)
    }

Here is the XML code for the destination to productItem

<fragment
    android:id="@+id/categoryProductItems2"
    android:name="com.sample.store.main.dashboard.ui.ui.home.categoryitems.CategoryProductItems"
    android:label="CategoryProductItems"
    tools:layout="@layout/fragment_category_product_items">
    <argument
        android:name="category_global"
        app:argType="com.sample.store.data.globalmodels.response.categories.Category" />
    <action
        android:id="@+id/action_categoryProductItems2_to_productItem"
        app:destination="@id/productItem"
        app:enterAnim="@anim/enter_from_right"
        app:exitAnim="@anim/exit_to_right"
        app:popEnterAnim="@anim/fragment_open_enter"
        app:popExitAnim="@anim/fragment_fade_exit" />
</fragment>

And here is the error:

java.lang.IllegalArgumentException: Navigation action/destination com.sample.store.full:id/action_categoryProductItems2_to_productItem cannot be found from the current destination Destination(id/navigation_home) label=Home class=com.sample.store.main.dashboard.ui.ui.home.mainui.HomeFragment

I don't know what happened, but it seems that the navController is looking for the "navigation_home"


Solution

  • Firstly you should not pass requireView() when trying to retrieve your Nav controller - navController = Navigation.findNavController(requireView()). You should be passing the actual Navigation Host Fragment instance.

    Secondly the issue is being caused because you are trying to call a Navigation path from B -> C, when on fragment A.

    Your direction path is from B -> C

    val action = CategoryProductItemsDirections.actionCategoryProductItems2ToProductItem(null, it)
    

    But you navigate up first so you are actually now on Fragment A when trying to execute the navigation:

    navController?.navigateUp()
    navController?.navigate(action)