Passing data to activity and fragment in Android

When passing data to an activity or a fragment in Android, the Bundle is used to contain the data and ship it to the activity or fragment to be launched. Bundle has put and get methods for all primitive types, Parcelables, and Serializables. In the following examples, the primitve type string is used for demonstration purpose.

To Activity

Passing data to activity using the putExtra() directly on the intent.

Intent intent = new Intent(this, MyActivity.class);
intent.putExtra('my_key', 'My String');

Passing data to activity using the Bundle from the Intent.

Intent intent = new Intent(this, MyActivity.class);
Bundle bundle = i.getExtras();
bundle.putString('my_key', 'My String');

Passing data to activity using a new Bundle.

Intent intent = new Intent(this, MyActivity.class);
Bundle bundle = new Bundle();
bundle.putString('my_key', 'My String');
intent.putExtras(bundle);

To retrieve the data from the launched activity in the onCreate method.

String value = getIntent().getExtras().getString('my_key');

To Fragment

Create a bunlde and put your key and value to it, then set the argument of the framgent with this bundle.

Bundle bundle = new Bundle();
bundle.putString("my_key", "My String");
MyFragment myFrag = new MyFragment();
myFrag.setArguments(bundle);

Retrieve the data back in the launched Fragment in the onCreateView method.

String myStr = getArguments().getString("my_key");    

More example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search