Sobes.tech
Junior — Middle

How can information obtained in one fragment be transmitted and used in another fragment during navigation between them?

sobes.tech AI

Answer from AI

In Android, to pass data between fragments, a Bundle is usually used — an object into which the necessary data is placed and then passed through the fragment's arguments. When navigating, you can:

  • Create a Bundle with the required data
  • Set it as arguments for a new fragment using setArguments()
  • In the new fragment, retrieve the Bundle via getArguments() and extract the data

Example of passing a string from one fragment to another:

Bundle bundle = new Bundle();
bundle.putString("key", "value");
Fragment fragment = new AnotherFragment();
fragment.setArguments(bundle);
// then perform the fragment transaction to replace

In the target fragment:

Bundle args = getArguments();
if (args != null) {
    String value = args.getString("key");
}

You can also use ViewModel for shared data storage between fragments within the same activity.