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.
[code language=”java”]
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra(‘my_key’, ‘My String’);
[/code]

Passing data to activity using the Bundle from the Intent.
[code language=”java”]
Intent intent = new Intent(this, MyActivity.class);
Bundle bundle = i.getExtras();
bundle.putString(‘my_key’, ‘My String’);
[/code]

Passing data to activity using a new Bundle.
[code language=”java”]
Intent intent = new Intent(this, MyActivity.class);
Bundle bundle = new Bundle();
bundle.putString(‘my_key’, ‘My String’);
intent.putExtras(bundle);
[/code]

To retrieve the data from the launched activity in the onCreate method.
[code language=”java”]
String value = getIntent().getExtras().getString(‘my_key’);
[/code]

To Fragment

Create a bunlde and put your key and value to it, then set the argument of the framgent with this bundle.
[code language=”java”]
Bundle bundle = new Bundle();
bundle.putString("my_key", "My String");
MyFragment myFrag = new MyFragment();
myFrag.setArguments(bundle);
[/code]

Retrieve the data back in the launched Fragment in the onCreateView method.
[code language=”java”]
String myStr = getArguments().getString("my_key");
[/code]

More example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search