Search code examples
androidnavigationandroid-architecture-navigationandroid-navigationandroid-navigation-graph

Arguments received as null while navigating to nested nav graph on Android


Here is the code for app_nav_graph.xml with a nested nav graph:

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

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

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.sd.android.ui.HomeFragment">
        <action
            android:id="@+id/action_homeFragment_to_nestedNavGraph"
            app:destination="@id/nested_nav_graph" />
    </fragment>
</navigation>

Here is nested_nav_graph.xml:

<navigation 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nested_nav_graph"
    app:startDestination="@id/nestedHomeFragment">
    <fragment
        android:id="@+id/nestedHomeFragment"
        android:name="com.sd.android.ui.NestedHomeFragment">
    </fragment>
</navigation>

And here is the navigation code placed inside HomeActivity (hosting NavHostFragment):

 navController.setGraph(R.navigation.app_nav_graph);
 Bundle bundle = new Bundle();
 bundle.putInt("key", 1);
 navController.navigate(R.id.action_homeFragment_to_nestedNavGraph);

The issue is that NestedHomeFragment is not receiving the passed bundle i.e. getArguments() is returning null.

Why is this happening? Any suggestions to fix this?

Thanks


Solution

  • In your code, you are creating your Bundle, but you aren't actually passing it to your call to navigate(). You need to do that for it to actually be sent onto your destination:

    Bundle bundle = new Bundle();
    bundle.putInt("key", 1);
    navController.navigate(R.id.action_homeFragment_to_nestedNavGraph, bundle);