java – Passing Data between BottomNavigation fragments via NavigationComponent-ThrowExceptions

Exception or error:

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

How to solve:

you can use SharedViewModel also in navigation docs Pass data between destinations they refer

In general, you should strongly prefer passing only the minimal amount
of data between destinations. For example, you should pass a key to
retrieve an object rather than passing the object itself, as the total
space for all saved states is limited on Android. If you need to pass
large amounts of data, consider using a ViewModel as described in
Share data between fragments.

###

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());

Leave a Reply

Your email address will not be published. Required fields are marked *