Skip to content

Android Sending Data Between Fragments and Activities

How to send and receive data between Fragments and Activities#

Activity to Activity#

Use extras on an Intent.

Send#

From an activity:

Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("EXTRA_ID", sessionId);
startActivity(intent);

From a fragment:

Intent intent = new Intent(requireActivity(), NewActivity.class);
intent.putExtra("EXTRA_ID", sessionId);
startActivity(intent);

Receive#

Intent intent = getIntent();
String sessionId = intent.getStringExtra("EXTRA_ID");

Activity to Fragment#

Use a Bundle.

Send#

Bundle bundle = new Bundle();
bundle.putString("BUNDLE_ID", sline);
NewFragment frag = new NewFragment();
frag.setArguments(bundle);

Receive#

String sline = getArguments().getString("BUNDLE_ID");

Fragment to Fragment#

Prefer the Fragment Result API for one-time results between fragments.

Bundle result = new Bundle();
result.putString("bundleKey", "result");
getParentFragmentManager().setFragmentResult("requestKey", result);

The receiving fragment registers a listener:

getParentFragmentManager().setFragmentResultListener(
    "requestKey",
    this,
    (requestKey, bundle) -> {
        String result = bundle.getString("bundleKey");
    }
);

For shared ongoing state, use a shared ViewModel scoped to the activity or navigation graph.

Sources#