Junior — Middle
What safe methods can be used to pass data between Fragments through the constructor?
sobes.tech AI
Answer from AI
In Android, passing data between Fragments directly through constructors is not recommended, as the system may recreate the fragment at any moment, calling the constructor without parameters. Instead, a safe and standard way is to use arguments via Bundle and the setArguments()/getArguments() methods.
Example of safe data passing:
class MyFragment : Fragment() {
companion object {
private const val ARG_PARAM = "param"
fun newInstance(param: String): MyFragment {
val fragment = MyFragment()
val args = Bundle()
args.putString(ARG_PARAM, param)
fragment.arguments = args
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val param = arguments?.getString(ARG_PARAM)
// Use param
}
}
Thus, data is stored in a Bundle, which the system automatically saves and restores during fragment recreation. Using constructors with parameters is unsafe and can lead to errors.
If you really want to use a constructor, you can make it empty and pass data through a Bundle, or use ViewModel for data exchange between fragments.