Search code examples
javaandroidandroid-fragmentsnavigationbottomnavigationview

Passing Data between BottomNavigation fragments via NavigationComponent


Is it possible to pass Parcelable object/arguments between BottomNavigation controlled Fragments via NavigationContoller?

Here is the flow of my app, user logs in to app and a fragment is opened which contains BottomNavigation. I was able to get the argument to first fragment(first fragment opens using NavHostFragment.findNavController(this).navigate(action) ) i was able to add arguments to this action and pass values, but BottomNavigation doesn't have any navigate instructions navigation is done via menuID. How can i pass logged in user argument between all these bottom navigated fragments via bundle.

I tried to pass arguments using onDestinationChanged()

@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
        NavArgument argument = new NavArgument.Builder().setDefaultValue(selectedUser).build();
        destination.addArgument("user", argument);
}

but still app crashes with java.lang.IllegalArgumentException: Required argument "user" is missing and does not have an android:defaultValue


Solution

  • We can either user SharedViewModel as asad has mentioned or we can use NavGraph to set argument

    navController.getGraph().findNode(R.id.todoFragment)
                .addArgument("user", new NavArgument.Builder()
                        .setDefaultValue(user)
                        .build());