Android Tutorial 3 – Starting an Activity with Results Returned

You will indefinitely have tasks you wish to carry out depending on what the user has done on a subsequent screen of your app this tutourial will explain how to start an activity so that the calling activity expects a result back and then how the calling activity can handle the result returned from the loaded activity.

Starting an Activity with the Expectation of a Result

Small difference from the usual way you would start an Activity:

Intent x = new Intent(this,ReceivingActivity.class);

startActivityForResult( Intent x, int 101);

To break it down startActivityForResult takes 2 variables: the first being the intent you use to load the activity and the second an identifier for this specific result.  The reason why is more apparent further down.

Setting the Result in the Loaded Activity

So the Activity that will return a result is ready to tell the calling Activity what has happened. To do this you call the function setResult(int result, Intent y) which takes one variable or more.  In order to return more detailed information you can make use of an intent otherwise return any number you wish to associate with the outcome that has occurred.  After setting the result simply close the Activity when necessary the Result is stored and will remain until the app returns to the calling Activity unless of course android needs the memory for more important things.

Retrieving the Result

After the app returns to the calling activity it will attempt to fire the following function:

protected void onActivityResult(int requestCode, int resultCode, Intent data)

So the breakdown:

requestCode is the identifier you gave the startActivityWithResult call at the beginning

resultCode is the outcome ID you gave in the setResult call

data is the intent, if present, in the setResult call

The request code will allow you to have multiple ActivityWithResult calls in one Activity and to personalise the handling of the result for each call uniquely using switches in the following format:


case 0:



      case 1:




Parting Words

My tutourials are infrequent to say the least, 2 years since my last one, but I will continue to post them when I find the time for it.





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s