49

I've started using Android Architecture Components (Navigation and Safe Args, View Models) along with Koin library.

Currently, I've got a problem with passing arguments between two fragments - I need to pass a string value from fragment A to fragment B, modify this value in fragment B and pass it back to fragment A.

I've found one possible solution to my problem - shared view models. Unfortunately, this approach has one problem because I can pass and modify values between screens, but when the fragment A navigate to another destination the value in the shared view model is still stored and not cleared.

Is there any different solution of passing and modifying data between fragments in Android Navigation? I want to avoid clearing this one value by hand (when the fragment A is destroyed).

4
  • did you solve it? Commented Oct 2, 2019 at 19:51
  • looking solution for a similar scenario. Is it solved, pls update? Commented Oct 30, 2019 at 11:34
  • 1
    See stackoverflow.com/questions/50754523/…. Basically, share a ViewModel. Commented Dec 3, 2019 at 21:34
  • Check out the answer here. They have just recently added the functionality to the Navigation library. Commented Mar 31, 2020 at 10:45

5 Answers 5

77

Android just released a solution for this; Passing data between Destinations (Navigation 2.3.0-alpha02), basically, in fragment A you observe changes in a variable and in fragment B you change that value before executing popBackStack().

Fragment A:

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")?.observe(viewLifecycleOwner) { result ->
    // Do something with the result.
}

Fragment B:

navController.previousBackStackEntry?.savedStateHandle?.set("key", result)
navController.popBackStack()
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! It works but this is very weird solution as compared to when you are passing data from Fragment A to Fragment B. This solution is more like old way of passing data using bundle as we are used used to do in Java.
can we pass multiple data using this?
Good job!!! Keep it up
Note: SavedStateHandle which Hilt injects into ViewModel and NavBackStackEntry SavedStateHandle are not the same objects. I spent several hours figuring this out
I needed a way to have an onBackPressed event in the Viewmodel. I searched for many many hours. This is the way.
|
3

You can use Fragment Result API.

Fragment A -> Fragment B

In Fragment A :

binding.buttonGo.setOnClickListener {
   setFragmentResultListener(ADD_LOCATION) { key, bundle ->
       clearFragmentResultListener(requestKey = ADD_LOCATION)
       val selectedLocationModel =
           bundle.getParcelable<LocationModel>(SELECTED_LOCATION_MODEL)
       this.selectedLocationModel = selectedLocationModel
   }
   navToFragmentB()
}

In Fragment B:

setFragmentResult(
    ADD_LOCATION,
    bundleOf(SELECTED_LOCATION_MODEL to selectedLocationModel)
)
goBack()

Do not forget to call clearFragmentResultListener() before create new one.

1 Comment

This one is very fine Answer. Thanks to you.
1

Currently, I've got a problem with passing arguments between two fragments - I need to pass a string value from fragment A to fragment B, modify this value in fragment B and pass it back to fragment A.

The theoretical solution really is to have the two fragments in a shared <navigation tag, then scope the ViewModel to the ID of the navigation tag, this way you now share the ViewModel between the two screens.

To make this reliable, it's best to use the NavBackStackEntry of the Navigation tag as both a ViewModelStoreOwner and SavedStateRegistryOwner, and create an AbstractSavedStateViewModelFactory that will create the ViewModel using the ViewModelProvider, while also giving you a SavedStateHandle.

You can communicate the results from FragmentB to FragmentA using this SavedStateHandle, associated with the shared ViewModel (scoped to the shared NavGraph).

Comments

0

You can try this solution

<fragment
    android:id="@+id/a"
    android:name="...">

    <argument
        android:name="text"
        app:argType="string" />

    <action
        android:id="@+id/navigate_to_b"
        app:destination="@id/b" />

</fragment>

<fragment
    android:id="@+id/b"
    android:name="...">

    <argument
        android:name="text"
        app:argType="string" />

    <action
        android:id="@+id/return_to_a_with_arguments"
        app:destination="@id/a"
        app:launchSingleTop="true"
        app:popUpTo="@id/b"
        app:popUpToInclusive="true" />

</fragment>

and navigation fragment

NavHostFragment.findNavController(this).navigate(BFragmentDirections.returnToAWithArguments(text))

ianhanniballake`s comment has helped me solve a similar problem

Comments

-7

1) Pass string from Fragment A to Fragment B with action_A_to_B and SafeArgs.

2) popBackStack to remove Fragment B.

navController.popBackStack(R.id.AFragment, false);

or

navController.popBackStack();

3) Then pass modified data from B to A with action_B_to_A.

EDIT.

Here you have some another solution

1 Comment

Your answer does not answer the passing back the arguments. It just remove the fragment from the navcontroller, that is it. Please reconsider your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.