Passing data to Activity and Fragment in Android - Example

Passing data to Activity and Fragment in Android - Example

Sometimes we need to send some valuable data to another activity or fragment, So, 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.

The bundle has put and get methods for all primitive types, Parcelables, and Serializable. In the following examples, the primitive type string is used for demonstration purpose.

First of all now see the How can I send data through Intent:

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

Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra('key', 'Hello World!');

Passing data to activity using a new Bundle.

Intent intent = new Intent(this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString('key', 'Hello world!');
intent.putExtras(bundle);

Now, look at there to retrieve the data from the launched activity in the onCreate method.

Loading...
String value = getIntent().getExtras().getString('key');

Now see the How can I send data to Fragment:

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

Bundle bundle = new Bundle();
bundle.putString("key", "Hello World!");
MyFragment myFrag = new MyFragment();
myFrag.setArguments(bundle);

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

String myString = getArguments().getString("key");

Related posts

Write a comment