Send data from activity to fragment in Android
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sending data from an activity to a fragment is a routine Android task, but the best technique depends on when that data is needed. If the fragment needs initial input when it is created, fragment arguments are the safest choice. If the data changes over time, a shared ViewModel usually scales better than repeatedly pushing values through fragment transactions.
The important distinction is lifecycle ownership. Fragments can be recreated by the system, so data should be delivered in a way that survives that recreation instead of relying on ad hoc field assignment.
Use Fragment Arguments for Initial Data
For initial values, put the data into the fragment's arguments bundle. A common pattern is a newInstance factory method in the fragment.
Then create and attach the fragment from the activity:
This pattern is recommended because the arguments bundle is restored with the fragment if Android recreates it after a configuration change or process death.
Use a Shared ViewModel for Ongoing Updates
Arguments are ideal for initial state, but they are not great for live updates. If both the activity and fragment need to observe the same changing data, use an activity-scoped ViewModel.
In the activity:
In the fragment:
This keeps the activity and fragment loosely coupled. The activity does not need to find the fragment and call a custom method directly.
Direct Method Calls Are Possible, but Use Them Carefully
If the fragment already exists and you control its lifetime tightly, the activity can find it and call a public method:
That works, but it is usually the least robust option. The activity must know which fragment instance exists, when it is attached, and whether its view is ready. For one-off UI nudges it can be fine, but it does not age as well as arguments or a shared ViewModel.
Common Pitfalls
- Passing data through a fragment constructor. Android may recreate the fragment later without that custom constructor call.
- Writing directly to public fragment fields and expecting the values to survive recreation.
- Putting very large objects into fragment arguments instead of using an identifier and loading the heavy data elsewhere.
- Calling fragment methods before the fragment is attached or before its view exists.
- Replacing fragment arguments when the real need is shared observable state.
Summary
- Use fragment arguments for initial data that the fragment needs at creation time.
- Read those arguments inside the fragment, not from the activity after the fact.
- Use an activity-scoped
ViewModelwhen the activity and fragment share changing state. - Prefer direct method calls only for tightly controlled, short-lived UI interactions.
- Think in terms of lifecycle safety first; that is what makes activity-to-fragment communication reliable.

