IllegalArgumentException: navigation destination xxx is unknown to this NavController

AndroidKotlinAndroid Architecture-NavigationAndroid NavigationAndroid Jetpack-Navigation

Android Problem Overview


I am having an issue with the new Android Navigation Architecture component when I try to navigate from one Fragment to another, I get this weird error:

java.lang.IllegalArgumentException: navigation destination XXX
is unknown to this NavController

Every other navigation works fine except this particular one.

I use findNavController() function of Fragment to get access to the NavController.

Any help will be appreciated.

Android Solutions


Solution 1 - Android

In my case, if the user clicks the same view twice very very quickly, this crash will occur. So you need to implement some sort of logic to prevent multiple quick clicks... Which is very annoying, but it appears to be necessary.

You can read up more on preventing this here: https://stackoverflow.com/questions/5608720/android-preventing-double-click-on-a-button/9950832

Edit 3/19/2019: Just to clarify a bit further, this crash is not exclusively reproducible by just "clicking the same view twice very very quickly". Alternatively, you can just use two fingers and click two (or more) views at the same time, where each view has their own navigation that they would perform. This is especially easy to do when you have a list of items. The above info on multiple click prevention will handle this case.

Edit 4/16/2020: Just in case you're not terribly interested in reading through that Stack Overflow post above, I'm including my own (Kotlin) solution that I've been using for a long time now.

OnSingleClickListener.kt
class OnSingleClickListener : View.OnClickListener {

    private val onClickListener: View.OnClickListener

    constructor(listener: View.OnClickListener) {
        onClickListener = listener
    }

    constructor(listener: (View) -> Unit) {
        onClickListener = View.OnClickListener { listener.invoke(it) }
    }

    override fun onClick(v: View) {
        val currentTimeMillis = System.currentTimeMillis()

        if (currentTimeMillis >= previousClickTimeMillis + DELAY_MILLIS) {
            previousClickTimeMillis = currentTimeMillis
            onClickListener.onClick(v)
        }
    }

    companion object {
        // Tweak this value as you see fit. In my personal testing this
        // seems to be good, but you may want to try on some different
        // devices and make sure you can't produce any crashes.
        private const val DELAY_MILLIS = 200L

        private var previousClickTimeMillis = 0L
    }

}
ViewExt.kt
fun View.setOnSingleClickListener(l: View.OnClickListener) {
    setOnClickListener(OnSingleClickListener(l))
}

fun View.setOnSingleClickListener(l: (View) -> Unit) {
    setOnClickListener(OnSingleClickListener(l))
}
HomeFragment.kt
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    settingsButton.setOnSingleClickListener {
        // navigation call here
    }
}

Solution 2 - Android

Check currentDestination before calling navigate might be helpful.

For example, if you have two fragment destinations on the navigation graph fragmentA and fragmentB, and there is only one action from fragmentA to fragmentB. calling navigate(R.id.action_fragmentA_to_fragmentB) will result in IllegalArgumentException when you were already on fragmentB. Therefor you should always check the currentDestination before navigating.

if (navController.currentDestination?.id == R.id.fragmentA) {
    navController.navigate(R.id.action_fragmentA_to_fragmentB)
}

Solution 3 - Android

You can check requested action in current destination of navigation controller.

UPDATE added usage of global actions for safe navigation.

fun NavController.navigateSafe(
        @IdRes resId: Int,
        args: Bundle? = null,
        navOptions: NavOptions? = null,
        navExtras: Navigator.Extras? = null
) {
    val action = currentDestination?.getAction(resId) ?: graph.getAction(resId)
    if (action != null && currentDestination?.id != action.destinationId) {
        navigate(resId, args, navOptions, navExtras)
    }
}

Solution 4 - Android

What I did to prevent the crash is the following:

I have a BaseFragment, in there I've added this fun to ensure that the destination is known by the currentDestination:

fun navigate(destination: NavDirections) = with(findNavController()) {
    currentDestination?.getAction(destination.actionId)
        ?.let { navigate(destination) }
}

Worth noting that I'm using the SafeArgs plugin.

Solution 5 - Android

It could also happen if you have a Fragment A with a ViewPager of Fragments B And you try to navigate from B to C

Since in the ViewPager the fragments are not a destination of A, your graph wouldn't know you are on B.

A solution can be to use ADirections in B to navigate to C

Solution 6 - Android

In my case I was using a custom back button for navigating up. I called onBackPressed() in stead of the following code

findNavController(R.id.navigation_host_fragment).navigateUp()

This caused the IllegalArgumentException to occur. After I changed it to use the navigateUp() method in stead, I didn't have a crash again.

Solution 7 - Android

Try that

  1. Create this extension function (or normal function):

UPDATED (without reflection and more readable)

import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.NavDirections
import androidx.navigation.fragment.DialogFragmentNavigator
import androidx.navigation.fragment.FragmentNavigator

fun Fragment.safeNavigateFromNavController(directions: NavDirections) {
    val navController = findNavController()
    when (val destination = navController.currentDestination) {
        is FragmentNavigator.Destination -> {
            if (javaClass.name == destination.className) {
                navController.navigate(directions)
            }
        }
        is DialogFragmentNavigator.Destination -> {
            if (javaClass.name == destination.className) {
                navController.navigate(directions)
            }
        }
    }
}

OLD (with reflection)

import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.NavDirections
import androidx.navigation.fragment.FragmentNavigator

inline fun <reified T : Fragment> NavController.safeNavigate(directions: NavDirections) {
    val destination = this.currentDestination as FragmentNavigator.Destination
    if (T::class.java.name == destination.className) {
        navigate(directions)
    }
}
  1. And use like this from your Fragment:
val direction = FragmentOneDirections.actionFragmentOneToFragmentTwo()
// new usage
safeNavigateFromNavController(direction)

// old usage
// findNavController().safeNavigate<FragmentOne>(action)

My problem was

I have a fragment (FragmentOne) that goes to two others fragments (FragmentTwo and FragmentThree). In some low devices, the user press button that redirects to FragmentTwo but in few milliseconds after the user press button that redirects to FragmentThree. The results is:

> Fatal Exception: java.lang.IllegalArgumentException Navigation > action/destination action_fragmentOne_to_fragmentTwo cannot be found > from the current destination Destination(fragmentThree) > class=FragmentThree

My solve was:

I check if the current destination belongs to the current fragment. If true, I execute the navigation acion.

That is all!

Solution 8 - Android

TL;DR Wrap your navigate calls with try-catch (simple way), or make sure there will be only one call of navigate in short period of time. This issue likely won't go away. Copy bigger code snippet in your app and try out.

Hello. Based on a couple of useful responses above, I would like to share my solution that can be extended.

Here is the code that caused this crash in my application:

@Override
public void onListItemClicked(ListItem item) {
    Bundle bundle = new Bundle();
    bundle.putParcelable(SomeFragment.LIST_KEY, item);
    Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);
}

A way to easily reproduce the bug is to tap with multiple fingers on the list of items where click on each item resolves in the navigation to the new screen (basically the same as people noted - two or more clicks in a very short period of time). I noticed that:

  1. First navigate invocation always works fine;
  2. Second and all other invocations of the navigate method resolve in IllegalArgumentException.

From my point of view, this situation may appear very often. Since the repeating of code is a bad practice and it is always good to have one point of influence I thought of the next solution:

public class NavigationHandler {

public static void navigate(View view, @IdRes int destination) {
    navigate(view, destination, /* args */null);
}

/**
 * Performs a navigation to given destination using {@link androidx.navigation.NavController}
 * found via {@param view}. Catches {@link IllegalArgumentException} that may occur due to
 * multiple invocations of {@link androidx.navigation.NavController#navigate} in short period of time.
 * The navigation must work as intended.
 *
 * @param view        the view to search from
 * @param destination destination id
 * @param args        arguments to pass to the destination
 */
public static void navigate(View view, @IdRes int destination, @Nullable Bundle args) {
    try {
        Navigation.findNavController(view).navigate(destination, args);
    } catch (IllegalArgumentException e) {
        Log.e(NavigationHandler.class.getSimpleName(), "Multiple navigation attempts handled.");
    }
}

}

And thus the code above changes only in one line from this:

Navigation.findNavController(recyclerView).navigate(R.id.action_listFragment_to_listItemInfoFragment, bundle);

to this:

NavigationHandler.navigate(recyclerView, R.id.action_listFragment_to_listItemInfoFragment, bundle);

It even became a little bit shorter. The code was tested in the exact place where the crash occurred. Did not experience it anymore, and will use the same solution for other navigations to avoid the same mistake further.

Any thoughts are welcome!

What exactly causes the crash

Remember that here we work with the same navigation graph, navigation controller and back-stack when we use method Navigation.findNavController.

We always get the same controller and graph here. When navigate(R.id.my_next_destination) is called graph and back-stack changes almost instantly while UI is not updated yet. Just not fast enough, but that is ok. After back-stack has changed the navigation system receives the second navigate(R.id.my_next_destination) call. Since back-stack has changed we now operate relative to the top fragment in the stack. The top fragment is the fragment you navigate to by using R.id.my_next_destination, but it does not contain next any further destinations with ID R.id.my_next_destination. Thus you get IllegalArgumentException because of the ID that the fragment knows nothing about.

This exact error can be found in NavController.java method findDestination.

Solution 9 - Android

In my case, the issue occurred when I had re-used one of my Fragments inside a viewpager fragment as a child of the viewpager. The viewpager Fragment(which was the parent fragment) was added in the Navigation xml, but the action was not added in the viewpager parent fragment.

nav.xml
//reused fragment
<fragment
    android:id="@+id/navigation_to"
    android:name="com.package.to_Fragment"
    android:label="To Frag"
    tools:layout="@layout/fragment_to" >
    //issue got fixed when i added this action to the viewpager parent also
    <action android:id="@+id/action_to_to_viewall"
        app:destination="@+id/toViewAll"/>
</fragment>
....
// viewpager parent fragment
<fragment
    android:id="@+id/toViewAll"
    android:name="com.package.ViewAllFragment"
    android:label="to_viewall_fragment"
    tools:layout="@layout/fragment_view_all">

Fixed the issue by adding the action to the parent viewpager fragment also as shown below:

nav.xml
//reused fragment
<fragment
    android:id="@+id/navigation_to"
    android:name="com.package.to_Fragment"
    android:label="To Frag"
    tools:layout="@layout/fragment_to" >
    //issue got fixed when i added this action to the viewpager parent also
    <action android:id="@+id/action_to_to_viewall"
        app:destination="@+id/toViewAll"/>
</fragment>
....
// viewpager parent fragment
<fragment
    android:id="@+id/toViewAll"
    android:name="com.package.ViewAllFragment"
    android:label="to_viewall_fragment"
    tools:layout="@layout/fragment_view_all"/>
    <action android:id="@+id/action_to_to_viewall"
        app:destination="@+id/toViewAll"/>
</fragment>

Solution 10 - Android

Today

> def navigationVersion = "2.2.1"

The issue still exists. My approach on Kotlin is:

// To avoid "java.lang.IllegalArgumentException: navigation destination is unknown to this NavController", se more https://stackoverflow.com/q/51060762/6352712
fun NavController.navigateSafe(
    @IdRes destinationId: Int,
    navDirection: NavDirections,
    callBeforeNavigate: () -> Unit
) {
    if (currentDestination?.id == destinationId) {
        callBeforeNavigate()
        navigate(navDirection)
    }
}

fun NavController.navigateSafe(@IdRes destinationId: Int, navDirection: NavDirections) {
    if (currentDestination?.id == destinationId) {
        navigate(navDirection)
    }
}

Solution 11 - Android

You can check before navigating if the Fragment requesting the navigation is still the current destination, taken from this gist.

It basically sets a tag on the fragment for later lookup.

/**
 * Returns true if the navigation controller is still pointing at 'this' fragment, or false if it already navigated away.
 */
fun Fragment.mayNavigate(): Boolean {

    val navController = findNavController()
    val destinationIdInNavController = navController.currentDestination?.id
    val destinationIdOfThisFragment = view?.getTag(R.id.tag_navigation_destination_id) ?: destinationIdInNavController

    // check that the navigation graph is still in 'this' fragment, if not then the app already navigated:
    if (destinationIdInNavController == destinationIdOfThisFragment) {
        view?.setTag(R.id.tag_navigation_destination_id, destinationIdOfThisFragment)
        return true
    } else {
        Log.d("FragmentExtensions", "May not navigate: current destination is not the current fragment.")
        return false
    }
}

R.id.tag_navigation_destination_id is just an id you'll have to add to your ids.xml, to make sure it's unique. <item name="tag_navigation_destination_id" type="id" />

More info on the bug and the solution, and navigateSafe(...) extention methods in "Fixing the dreaded “… is unknown to this NavController”

Solution 12 - Android

In my case, I had multiple nav graph files and I was trying to move from 1 nav graph location to a destination in another nav graph.

For this we have to include the 2nd nav graph in the 1st one like this

<include app:graph="@navigation/included_graph" />

and add this to your action:

<action
        android:id="@+id/action_fragment_to_second_graph"
        app:destination="@id/second_graph" />

where second_graph is :

<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/second_graph"
    app:startDestination="@id/includedStart">

in the second graph.

More info here

Solution 13 - Android

I have resolved the same problem by putting check before navigate instead of boilerplate code for clicking instantly control

 if (findNavController().currentDestination?.id == R.id.currentFragment) {
        findNavController().navigate(R.id.action_current_next)}
/* Here R.id.currentFragment is the id of current fragment in navigation graph */

according to this answer

https://stackoverflow.com/a/56168225/7055259

Solution 14 - Android

In my case the bug ocurred because I had a navigation action with the Single Top and the Clear Task options enabled after a splash screen.

Solution 15 - Android

It seems that mixing fragmentManager control of the backstack and Navigation Architecture control of the backstack can cause this issue also.

For example the original CameraX basic sample used fragmentManager backstack navigation as below and it appears as if it did not correctly interact with Navigation:

// Handle back button press
        view.findViewById<ImageButton>(R.id.back_button).setOnClickListener {
            fragmentManager?.popBackStack()
        }

If you log the 'current destination' with this version before moving from the main fragment (the camera fragment in this case) and then log it again when you return to the main fragment, you can see from the id in the logs that the id is not the same. At a guess, the Navigation updated it when moving to the fragment and the fragmntManager did not then update it again when moving back. From the logs:

> Before: D/CameraXBasic: currentDest?: androidx.navigation.fragment.FragmentNavigator$Destination@b713195 > > After: D/CameraXBasic: currentDest?: androidx.navigation.fragment.FragmentNavigator$Destination@9807d8f

The updated version of CameraX basic sample uses Navigation to return like this:

 // Handle back button press
        view.findViewById<ImageButton>(R.id.back_button).setOnClickListener {
            Navigation.findNavController(requireActivity(), R.id.fragment_container).navigateUp()
        }

This works correctly and the logs show the same id when back at the main fragment.

> Before: D/CameraXBasic: currentDest?: androidx.navigation.fragment.FragmentNavigator$Destination@b713195 > > After: D/CameraXBasic: currentDest?: androidx.navigation.fragment.FragmentNavigator$Destination@b713195

I suspect the moral of the story, at least at this time, is to be very careful mixing Navigation with fragmentManager navigation.

Solution 16 - Android

A Ridiculous way but very powerful is: Simply call this:

view?.findNavController()?.navigateSafe(action)

Just Create this Extention:

fun NavController.navigateSafe(
    navDirections: NavDirections? = null
) {
    try {
        navDirections?.let {
            this.navigate(navDirections)
        }
    }
    catch (e:Exception)
    {
        e.printStackTrace()
    }
}

Solution 17 - Android

I wrote this extensions

fun Fragment.navigateAction(action: NavDirections) {
    val navController = this.findNavController()
    if (navController.currentDestination?.getAction(action.actionId) == null) {
        return
    } else {
        navController.navigate(action)
    }
}

Solution 18 - Android

After thinking over Ian Lake's advice in this twitter thread I've came up with following approach. Having NavControllerWrapper defined as such:

class NavControllerWrapper constructor(
  private val navController: NavController
) {

  fun navigate(
    @IdRes from: Int,
    @IdRes to: Int
  ) = navigate(
    from = from,
    to = to,
    bundle = null
  )

  fun navigate(
    @IdRes from: Int,
    @IdRes to: Int,
    bundle: Bundle?
  ) = navigate(
    from = from,
    to = to,
    bundle = bundle,
    navOptions = null,
    navigatorExtras = null
  )

  fun navigate(
    @IdRes from: Int,
    @IdRes to: Int,
    bundle: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Navigator.Extras?
  ) {
    if (navController.currentDestination?.id == from) {
      navController.navigate(
        to,
        bundle,
        navOptions,
        navigatorExtras
      )
    }
  }

  fun navigate(
    @IdRes from: Int,
    directions: NavDirections
  ) {
    if (navController.currentDestination?.id == from) {
      navController.navigate(directions)
    }
  }

  fun navigateUp() = navController.navigateUp()

  fun popBackStack() = navController.popBackStack()
}

Then in navigation code:

val navController = navControllerProvider.getNavController()
navController.navigate(from = R.id.main, to = R.id.action_to_detail)

Solution 19 - Android

I resolve this issue by checking if the next action exist in the current destination

public static void launchFragment(BaseFragment fragment, int action) {
    if (fragment != null && NavHostFragment.findNavController(fragment).getCurrentDestination().getAction(action) != null) {       
        NavHostFragment.findNavController(fragment).navigate(action);
    }
}

public static void launchFragment(BaseFragment fragment, NavDirections directions) {
    if (fragment != null && NavHostFragment.findNavController(fragment).getCurrentDestination().getAction(directions.getActionId()) != null) {       
        NavHostFragment.findNavController(fragment).navigate(directions);
    }
}

This resolve a problem if the user click fast on 2 differents button

Solution 20 - Android

As mentioned in other answers, this exception generally occurs when a user

  1. clicks on multiple views at the same time that handle navigation
  2. clicks multiple times on a view that handles navigation.

Using a timer to disable clicks is not an appropriate way to handle this issue. If the user has not been navigated to the destination after the timer expires the app will crash anyways and in many cases where navigation is not the action to be performed quick clicks are necessary.

In case 1, android:splitMotionEvents="false" in xml or setMotionEventSplittingEnabled(false) in source file should help. Setting this attribute to false will allow only one view to take the click. You can read about it here

In case 2, there would be something delaying the navigation process allowing the user to click on a view multiple times(API calls, animations, etc). The root issue should be resolved if possible so that navigation happens instantaneously, not allowing the user to click the view twice. If the delay is inevitable, like in the case of an API call, disabling the view or making it unclickable would be the appropriate solution.

Solution 21 - Android

In order to avoid this crash one of my colleagues wrote a small library which exposes a SafeNavController, a wrapper around the NavController and handles the cases when this crash occurs because of multiple navigate commands at the same time.

Here is a short article about the whole issue and the solution.

You can find the library here.

Solution 22 - Android

Yet another solution to the same quick-click-navigation-crash problem:

fun NavController.doIfCurrentDestination(@IdRes destination: Int, action: NavController.()-> Unit){
    if(this.currentDestination?.id == destination){action()}
}

and then use like this:

findNavController().doIfCurrentDestination(R.id.my_destination){ navigate(...) }

benefits of this solutions is that you can easily wrap any existing call to naviagte() with whatever signature you already use, no need to make a million overloads

Solution 23 - Android

I got this same error because I used a Navigation Drawer and getSupportFragmentManager().beginTransaction().replace( ) at the same time somewhere in my code .

I got rid of the error by using this condition(testing if the destination) :

if (Navigation.findNavController(v).getCurrentDestination().getId() == R.id.your_destination_fragment_id)
Navigation.findNavController(v).navigate(R.id.your_action);

In my case the previous error was triggered when I was clicking on the navigation drawer options. Basically the code above did hide the error , because in my code somewhere I used navigation using getSupportFragmentManager().beginTransaction().replace( ) The condition -

 if (Navigation.findNavController(v).getCurrentDestination().getId() ==
  R.id.your_destination_fragment_id) 

was never reached because (Navigation.findNavController(v).getCurrentDestination().getId() was always poiting to home fragment. You must only use Navigation.findNavController(v).navigate(R.id.your_action) or nav graph controller functions for all your navigation actions.

Solution 24 - Android

There could be many reasons for this problem. In my case i was using the MVVM model and i was observing a boolean for navigation when the boolean is true -> navigate else don't do anything and this was working fine but there was one mistake here

when pressing back button from the destination fragment i was encountering the same problem .And problem was the boolean object as I forgot to change the boolean value to false this created the mess.I just created a function in viewModel to change its value to false and called it just after the findNavController()

Solution 25 - Android

Update to @AlexNuts answer to support navigating to a nested graph. When an action uses a nested graph as a destination like so:

<action
    android:id="@+id/action_foo"
    android:destination="@id/nested_graph"/>

The destination ID of this action cannot be compared with the current destination because the current destination cannot be a graph. The start destination of the nested graph must be resolved.

fun NavController.navigateSafe(directions: NavDirections) {
    // Get action by ID. If action doesn't exist on current node, return.
    val action = (currentDestination ?: graph).getAction(directions.actionId) ?: return
    var destId = action.destinationId
    val dest = graph.findNode(destId)
    if (dest is NavGraph) {
        // Action destination is a nested graph, which isn't a real destination.
        // The real destination is the start destination of that graph so resolve it.
        destId = dest.startDestination
    }
    if (currentDestination?.id != destId) {
        navigate(directions)
    }
}

However this will prevent navigating to the same destination twice, which is sometimes needed. To allow that, you can add a check to action.navOptions?.shouldLaunchSingleTop() and add app:launchSingleTop="true" to the actions for which you don't want duplicated destinations.

Solution 26 - Android

I caught this exception after some renames of classes. For example: I had classes called FragmentA with @+is/fragment_a in navigation graph and FragmentB with @+id/fragment_b. Then I deleted FragmentA and renamed FragmentB to FragmentA. So after that node of FragmentA still stayed in navigation graph, and android:name of FragmentB's node was renamed path.to.FragmentA. I had two nodes with the same android:name and different android:id, and the action I needed were defined on node of removed class.

Solution 27 - Android

It occurs to me when I press the back button two times. At first, I intercept KeyListener and override KeyEvent.KEYCODE_BACK. I added the code below in the function named OnResume for the Fragment, and then this question/issue is solved.

  override fun onResume() {
        super.onResume()
        view?.isFocusableInTouchMode = true
        view?.requestFocus()
        view?.setOnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                activity!!.finish()
                true
            }
            false
        }
    }

When it happens to me for a second time, and it's status is the same as the first one, I find that I maybe use the adsurd function. Let’s analyze these situations.

  1. Firstly, FragmentA navigates to FragmentB ,then FragmentB navigates to FragmentA, then press back button... the crash appears.

  2. Secondly, FragmentA navigates to FragmentB, then FragmentB navigates to FragmentC, FragmentC navigates to FragmentA, then press back button... the crash appears.

So I think when pressing back button, FragmentA will return to FragmentB or FragmentC, then it causes the login mess. Finally I find that the function named popBackStack can be used for back rather than navigate.

  NavHostFragment.findNavController(this@TeacherCloudResourcesFragment).
                        .popBackStack(
                            R.id.teacher_prepare_lesson_main_fragment,false
                        )

So far, the problem is really solved.

Solution 28 - Android

If you click on too quickly , it will cause null and crash.

We can use RxBinding lib to help on this. You can add throttle and duration on the click before it happens.

 RxView.clicks(view).throttleFirst(duration, TimeUnit.MILLISECONDS)
            .subscribe(__ -> {
            });

These articles on throttling on Android might help. Cheers!

Solution 29 - Android

I am calling the 2.3.1 Navigation and the same error occurs when the application configuration changes. When the cause of the problem was found through Debug, the GaphId in NavHostFragment did not take effect as the ID currently set by calling navController.setGraph(). The GraphId of NavHostFragment can only be obtained from the <androidx.fragment.app.FragmentContainerView/> tag. At this time, this problem will occur if there are multiple GraphIds dynamically set in your code. When the interface is restored, the Destination cannot be found in the cached GraphId. You can solve this problem by manually specifying the value of mGraphId in NavHostFragment through reflection when switching Graph.

navController.setGraph(R.navigation.home_book_navigation);
try {
    Field graphIdField = hostFragment.getClass().getDeclaredField("mGraphId");
    graphIdField.setAccessible(true);
    graphIdField.set(navHostFragment, R.navigation.home_book_navigation);
} catch (NoSuchFieldException | IllegalAccessException e) {
    e.printStackTrace();
}

Solution 30 - Android

Throwing my answer into the ring that handles the two cases (double tap, simultaneous tap on two buttons) elegantly yet tries to not mask real errors.

We can use a navigateSafe() function that checks to see if the destination that we're trying to navigate to is invalid from the current destination but is valid from the previous destination. If this is the case, the code assumes the user either double tapped or tapped two buttons simultaneous.

This solution isn't perfect however as it may mask real problems in niche cases where we try to navigate to something that just so happens to be a destination of the parent. It is assumed though that this would be unlikely.

Code:

fun NavController.navigateSafe(directions: NavDirections) {
    val navigateWillError = currentDestination?.getAction(directions.actionId) == null

    if (navigateWillError) {
        if (previousBackStackEntry?.destination?.getAction(directions.actionId) != null) {
            // This is probably some user tapping two different buttons or one button twice quickly
            // Ignore...
            return
        }

        // This seems like a programming error. Proceed and let navigate throw.
    }

    navigate(directions)
}

Solution 31 - Android

It seems like you are clearing task. An app might have a one-time setup or series of login screens. These conditional screens should not be considered the starting destination of your app.

https://developer.android.com/topic/libraries/architecture/navigation/navigation-conditional

Solution 32 - Android

This happened to me, my issue was I was clicking a FAB on tab item fragment. I was trying to navigate from one of tab item fragment to another fragment.

But according to Ian Lake in this answer we have to use tablayout and viewpager, no navigation component support. Because of this, there is no navigation path from tablayout containing fragment to tab item fragment.

ex:

containing fragment -> tab layout fragment -> tab item fragment -> another fragment

Solution was to create a path from tab layout containing fragment to intended fragment ex: path: container fragment -> another fragment

Disadvantage:

  • Nav graph no longer represent user flow accurately.

Solution 33 - Android

Updated @Alex Nuts solution

If there is no action for particular fragment and want to navigate to fragment

fun NavController.navigateSafe(
@IdRes actionId: Int, @IdRes fragmentId: Int, args: Bundle? = null,
navOptions: NavOptions? = null, navExtras: Navigator.Extras? = null) 
{
  if (actionId != 0) {
      val action = currentDestination?.getAction(actionId) ?: graph.getAction(actionId)
      if (action != null && currentDestination?.id != action.destinationId) {
          navigate(actionId, args, navOptions, navExtras)
    }
    } else if (fragmentId != 0 && fragmentId != currentDestination?.id)
        navigate(fragmentId, args, navOptions, navExtras)
}

Solution 34 - Android

Usually when this happens to me, I had the issue described by Charles Madere: Two navigation events triggered on the same ui, one changing the currentDestination and the other failing because the currentDestination is changed. This can happen if you double-tap, or click on two views with a click listener calling findNavController.navigate.

So to resolve this you can either use if-checks, try-catch or if you are interested there is a findSafeNavController() which does this checks for you before navigating. It also has a lint-check to make sure you don't forget about this issue.

GitHub

Article detailing the issue

Solution 35 - Android

I created this extension function for Fragment:

fun Fragment.safeNavigate(
    @IdRes actionId: Int,
    @Nullable args: Bundle? = null,
    @Nullable navOptions: NavOptions? = null,
    @Nullable navigatorExtras: Navigator.Extras? = null
) {
    NavHostFragment.findNavController(this).apply {
        if (currentDestination?.label == this@safeNavigate::class.java.simpleName) {
            navigate(actionId, args, navOptions, navigatorExtras)
        }
    }
}

Solution 36 - Android

If you're using a recyclerview just add a click listener cooldown on your click and also in your recyclerview xml file use android:splitMotionEvents="false"

Solution 37 - Android

To prevent crash, I recommend to use safeargs plugin otherwise you need to check everytime destination id exists or not. Other thing is in your menu file for bottomnavigationview, each item id has to same as fragment id which is added in navigation graph xml file.

If you use kotlin, you need to add some dependencies in your build.gradle.

android{
compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

dependencies {
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.1'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.1'
}

For SafeArgs

dependencies {
classpath  'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0'
}

To navigate to destination, First you have to connect them through action in your navigation graph xml file.

<fragment
        android:id="@+id/employeesListFragment"
        android:name="com.example.navigationjetpacksample.fragments.EmployeesListFragment"
        android:label="EmployeesListFragment"
        tools:layout="@layout/frag_employees_list">
        <action
            android:id="@+id/action_employeesListFragment_to_addEmployeeFragment"
            app:destination="@id/addEmployeeFragment" />
    </fragment>

After build/clean your project,

 fab_add.setOnClickListener {   it.findNavController().navigate(EmployeesListFragmentDirections.actionEmployeesListFragmentToAddEmployeeFragment())
 }

For more reference: Jetpack Navigation Example

Solution 38 - Android

Answered in link: https://stackoverflow.com/a/67614469/5151336

Added extension function for Navigator for safe navigation.

Solution 39 - Android

I was having this same issue in my projects, first I tried to debounce the clicks on the view that was triggering the navigation action, but after some experimenting I found that on really slow devices the debounce should be a very high value that causes the app to feel slow for users with fast devices.

So I came up with the following extensions for NavController, I think it is in line with the original API and is easy to use:

fun NavController.safeNavigate(directions: NavDirections) {
    try {
        currentDestination?.getAction(directions.actionId) ?: return
        navigate(directions.actionId, directions.arguments, null)
    } catch (e : Exception) {
        logError("Navigation error", e)
    }
}

fun NavController.safeNavigate(directions: NavDirections, navOptions: NavOptions?) {
    try {
        currentDestination?.getAction(directions.actionId) ?: return
        navigate(directions.actionId, directions.arguments, navOptions)
    } catch (e : Exception) {
        logError("Navigation error", e)
    }
}

fun NavController.safeNavigate(directions: NavDirections, navigatorExtras: Navigator.Extras) {
    try {
        currentDestination?.getAction(directions.actionId) ?: return
        navigate(directions.actionId, directions.arguments, null, navigatorExtras)
    } catch (e : Exception) {
        logError("Navigation error", e)
    }
}

Please note that I am using SafeArgs and NavDirections. These functions check if the action is valid from the current destination and only navigate if the action is not null. The try catch part should not be necessary if the Navigation library returns the correct action every time, but I wanted to eliminate all possible crashes.

Solution 40 - Android

This error may have occured because you may have assigned the target screen to the wrong graph

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJerry OkaforView Question on Stackoverflow
Solution 1 - AndroidCharles MadereView Answer on Stackoverflow
Solution 2 - AndroidtheJianView Answer on Stackoverflow
Solution 3 - AndroidAlex NutsView Answer on Stackoverflow
Solution 4 - AndroidDouglas KazumiView Answer on Stackoverflow
Solution 5 - AndroidAntPachonView Answer on Stackoverflow
Solution 6 - Androidthe-ginger-geekView Answer on Stackoverflow
Solution 7 - AndroidAbner EscócioView Answer on Stackoverflow
Solution 8 - AndroidJenea VranceanuView Answer on Stackoverflow
Solution 9 - Androidhushed_voiceView Answer on Stackoverflow
Solution 10 - AndroidSerg BurlakaView Answer on Stackoverflow
Solution 11 - AndroidFrankView Answer on Stackoverflow
Solution 12 - Androidhushed_voiceView Answer on Stackoverflow
Solution 13 - AndroidmohammadView Answer on Stackoverflow
Solution 14 - AndroidEury Pérez BeltréView Answer on Stackoverflow
Solution 15 - AndroidMickView Answer on Stackoverflow
Solution 16 - AndroidAmir Hossein GhasemiView Answer on Stackoverflow
Solution 17 - AndroidOleksandr YahnenkoView Answer on Stackoverflow
Solution 18 - AndroidazizbekianView Answer on Stackoverflow
Solution 19 - AndroidVodetView Answer on Stackoverflow
Solution 20 - AndroidXidView Answer on Stackoverflow
Solution 21 - AndroidNagy ArthurView Answer on Stackoverflow
Solution 22 - AndroidMardannView Answer on Stackoverflow
Solution 23 - AndroidAnessView Answer on Stackoverflow
Solution 24 - AndroidManoj ChouhanView Answer on Stackoverflow
Solution 25 - AndroidNicolasView Answer on Stackoverflow
Solution 26 - AndroidVasyaFromRussiaView Answer on Stackoverflow
Solution 27 - Android唐德坤View Answer on Stackoverflow
Solution 28 - AndroidJoshuaView Answer on Stackoverflow
Solution 29 - AndroidwangkeView Answer on Stackoverflow
Solution 30 - AndroididunnololzView Answer on Stackoverflow
Solution 31 - AndroidPatrickView Answer on Stackoverflow
Solution 32 - Androiduser158View Answer on Stackoverflow
Solution 33 - AndroidSumitView Answer on Stackoverflow
Solution 34 - AndroidGergely HegedusView Answer on Stackoverflow
Solution 35 - AndroidMehmedView Answer on Stackoverflow
Solution 36 - AndroidCrazyView Answer on Stackoverflow
Solution 37 - AndroidDhrumil ShahView Answer on Stackoverflow
Solution 38 - Androidvishnu bennyView Answer on Stackoverflow
Solution 39 - AndroidKozma Zoltán BalázsView Answer on Stackoverflow
Solution 40 - AndroidMax ZonovView Answer on Stackoverflow