Search code examples
androidandroidxandroid-navigation-graph

Navigate to fragment with NavController from notification


I need to navigate to a fragment, when the user clicks a notification.

This works fine if the app is running. However when I quit the app, and then click on the notification it crashes with this error message:

2020-04-24 18:06:49.607 14832-14832/com.package.name E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.package.name, PID: 14832
java.lang.IllegalStateException: no current navigation node
    at androidx.navigation.NavController.navigate(NavController.java:824)
    at androidx.navigation.NavController.navigate(NavController.java:804)
    at androidx.navigation.NavController.navigate(NavController.java:790)
    at androidx.navigation.NavController.navigate(NavController.java:985)
    at com.package.name.core.navigation.NavigationActivity.handleNewIntent(NavigationActivity.kt:358)
    at com.package.name.core.navigation.NavigationActivity.onPostCreate(NavigationActivity.kt:257)
    at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1385)
    at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3088)
    at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
    at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
    at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6863)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

My code doing the navigation:

navController.navigate(
                navigateToFragment(
                    someParam = "some value",
                    someOtherParam = "other value"
                )
            )

How my navController is instanciated

private val navController: NavController by lazy {
    Navigation.findNavController(this, R.id.nav_host_fragment)
}

I guess this is due to my navController not being properly initialized? Any ideas how to fix this/what is the right way to do it?


Solution

  • I found the solution.

    What was missing was setting the start destination for my navcontroller, like this:

      graph = navGraph.apply { startDestination = destinationId }
      currentDestination?.let { applyDestinationPropertiesToToolbar(it) }