Junior — Middle
How to pass object data between two fragments in an application?
sobes.tech AI
Answer from AI
To pass data between two fragments in Android, arguments (Bundle) are usually used.
Main methods:
-
Via Bundle in setArguments/getArguments
- In the first fragment, create a Bundle, put data into it (primitives, Serializable, Parcelable).
- Set the Bundle to the second fragment using setArguments.
- In the second fragment, retrieve data through getArguments.
-
Via ViewModel (if fragments belong to the same Activity)
- Create a shared ViewModel.
- The first fragment writes data into the ViewModel.
- The second fragment reads data from the ViewModel.
Example of passing data via Bundle:
// In the first fragment
Bundle bundle = new Bundle();
bundle.putString("key", "value");
SecondFragment fragment = new SecondFragment();
fragment.setArguments(bundle);
// In the second fragment
@Override
public View onCreateView(...) {
Bundle args = getArguments();
if (args != null) {
String value = args.getString("key");
}
// ...
}
If the object is complex, it is recommended to implement Parcelable for efficient data transfer.