Two ways to send data to previous fragment
- With setFragmentResult
- With BackStackEntry
Let’s say there are two fragments fragmentA and fragmentB.
With setFragmentResult
In FragmentB write:
Call this method to Set data and Go back in FragmentA.
private fun sendDataToFragmentA() {
val result = "Data from FragmentB"
setFragmentResult("result_key", bundleOf("data" to result))
findNavController().navigateUp()
}
If you want to send data onBack key pressed then modify above code like this [Without NavGraph]
override fun onPause() {
super.onPause()
val result = "Data from FragmentB"
setFragmentResult("result_key", bundleOf("data" to result))
}
Listen to this in FragmentA:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Register to listen for the result in FragmentA
setFragmentResultListener("result_key") { _, bundle ->
val data = bundle.getString("data")
// Handle the received data here
}
}
With BackStackEntry
Here the data has to be set while the fragment is in onResume() state. If the data is set after onResume() method, it will not be set.
In FragmentB:
override fun onResume() {
super.onResume()
findNavController()
.previousBackStackEntry
?.savedStateHandle
?.set("key", "Data from FragmentB")
}
In FragmentA:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val liveData = findNavController()
.currentBackStackEntry
?.savedStateHandle
?.getLiveData<String>("key")
liveData?.observe(viewLifecycleOwner) { data ->
// Handle the received data here
}
}