Passing values to activities using Extras: Android Programming @DrBFraser
Passing values to activities using Extras: Android Programming  @DrBFraser
Uploaded February 2014 | Updated November 2026, 3 hours ago
Demonstrate passing a value to an activity when it is created, and passing a value back (returning) when it finishes. Complete source code available at github.com/drbfraser/video-tutorial-code/tree/master/ExtrasDemo

Passing To an Activity:
-----------------------
Pass data to an activity from MainActivity:
Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
intent.putExtra("my parameter name", 42);
startActivity(intent);

Getting value in second activity's onCreate():
Intent intent = getIntent();
int myValue = intent.getIntExtra("my parameter name", 0);
// 0 is the default value if the parameter not set.


Returning a value:
------------------
Change calling code (1st activity) to use startActivityForResult():
Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
intent.putExtra("my parameter name", 42);
startActivityForResult(intent, 12345);
// 12345 is a code to myself to identify which call is returning.

Set data in the called activity (2nd activity):
Intent returnData = new Intent();
returnData.putExtra("my answer", 24);
setResult(Activity.RESULT_OK, returnData);
// use Activity.RESULT_CANCELED to indicate failure.
finish();

Catch the return value in 1st activity's onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch(requestCode) {
case 12345:
if (resultCode == Activity.RESULT_OK) {

int answer = data.getIntExtra("my answer", 0);
// 0 is default value if none was specified

// Do something with the answer...
break;
}
}
Passing values to activities using Extras: Android ProgrammingInstall VMWare Player & Creating an Ubuntu VMCreating a Robotium test project for an Android application.Internationalization: Android TutorialButton Tutorial: Android ProgrammingSubversive: Ignore bin/ and gen/ foldersChecking out an existing project: Git & EclipsePost changes to AppServer: Android ProgrammingListView with Images and Text: Android ProgrammingConfigure a VMWare Player VMReturn Data From Activity: Android ProgrammingModel / View Separation: Java for Programmers
Brian Fraser |

Passing values to activities using Extras: Android Programming

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER