Android
Activity
Fragment
Data Transfer
Mobile Development

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.

kotlin
1class DetailsFragment : Fragment(R.layout.fragment_details) {
2
3    companion object {
4        private const val ARG_USER_ID = "user_id"
5
6        fun newInstance(userId: String): DetailsFragment {
7            return DetailsFragment().apply {
8                arguments = bundleOf(ARG_USER_ID to userId)
9            }
10        }
11    }
12
13    override fun onCreate(savedInstanceState: Bundle?) {
14        super.onCreate(savedInstanceState)
15        val userId = requireArguments().getString(ARG_USER_ID)
16        check(!userId.isNullOrEmpty())
17    }
18}

Then create and attach the fragment from the activity:

kotlin
1class MainActivity : AppCompatActivity(R.layout.activity_main) {
2    override fun onCreate(savedInstanceState: Bundle?) {
3        super.onCreate(savedInstanceState)
4
5        if (savedInstanceState == null) {
6            supportFragmentManager.commit {
7                replace(R.id.container, DetailsFragment.newInstance("42"))
8            }
9        }
10    }
11}

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.

kotlin
1class SharedViewModel : ViewModel() {
2    private val _selectedUser = MutableLiveData<String>()
3    val selectedUser: LiveData<String> = _selectedUser
4
5    fun selectUser(userId: String) {
6        _selectedUser.value = userId
7    }
8}

In the activity:

kotlin
1class MainActivity : AppCompatActivity(R.layout.activity_main) {
2    private val viewModel: SharedViewModel by viewModels()
3
4    fun onUserClicked(userId: String) {
5        viewModel.selectUser(userId)
6    }
7}

In the fragment:

kotlin
1class DetailsFragment : Fragment(R.layout.fragment_details) {
2    private val viewModel: SharedViewModel by activityViewModels()
3
4    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
5        viewModel.selectedUser.observe(viewLifecycleOwner) { userId ->
6            renderUser(userId)
7        }
8    }
9
10    private fun renderUser(userId: String) {
11        // Update the UI with the selected user.
12    }
13}

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:

kotlin
val fragment = supportFragmentManager.findFragmentById(R.id.container) as? DetailsFragment
fragment?.showStatus("Connected")

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 ViewModel when 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.

Course illustration
Course illustration

All Rights Reserved.