Using putExtra() and getExtras() in android

Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example an Activity can send an Intents to the Android system which starts another Activity.

putExtra() adds extended data to the intent.

It has two parameters, first one specifies the  name which of the extra data,and the second parameter is the data itself.
getExtra() fetches data which was added using putExtra() in the following way:

Bundle extras= getIntent().getExtras();

Bundle is basically a mapping from String values to various Parcelable types.

getIntent() returns the intent that started this activity.

The below example shows the usage :

Example:


//Intent created from FirstScreen to SecondScreen

Intent i = new Intent(FirstScreen.this, SecondScreen.class);

String keyIdentifer  = null;

i.putExtra("STRING_I_NEED", strName);//adding additional data using putExtras()

Then, to retrieve the value you can use the below mentioned code:

Bundle extras;

String newString;

if (savedInstanceState == null)

{

//fetching extra data passed with intents in a Bundle type variable

extras = getIntent().getExtras();

if(extras == null)

{        newString= null;

}

else

{            /* fetching the string passed with intent using ‘extras’*/

newString= extras.getString("STRING_I_NEED");

}

}

Advertisements