3. onActivityResult Android Tutorial

This entry is part 3 of 22 in the series Android-Intermediate

Mybringback Android Tutorials Icon for onActivityResult tutorialGet The Data Results

by using Android’s onActivityResult method!

In this Android tutorial we be getting data from another activity via onActivityResult.   After we set the result, we’ll have to catch this information.  In the previous tutorial we learned how to open an activity for a result and how to set that result (make sure you check that out here first), but now we will learn about how to safely get that result.  If you haven’t programmed with Android before, or if you think I’m moving a little fast in this tutorial, you should start with the Android basics series.


Android’s onActivityResult Walk-through


Android onActivityResult() Tutorial

According to the Android Developers Page, onActivityResult is “Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.”

Since we opened an Activity for a result (using the startActivityForResult method), once that activity exits, the onActivityResult method will get called, and it will handled the result however we choose.

First, let’s break down the three parameters for the onActivityResult method, requestCode, resultCode, and data. When we started the activity for result in the previous tutorial, we used two parameters, the intent (which held the activity we wanted to open and the extras) and the requestCode (which we set at 1, but it could be any integer we want).  After we set the result and send the data back to the first Activity and the onActivityResult method is called, we will be able to determine which request we made from the request code.

For example, if in Activity1 we had two methods that opened another activity to get some data and set it to a variable (say width and height), we could use the requestCode to determine which variable is looking for the data.

(Getting information for the variables, we could arbitrarily set the width requestCode to 1, and the height requestCode to 2.)
Looking for width:  startActivityForResult(i, 1);
Looking for height: startActivityForResult(i,2);

After calling something like this, it would open up Activity2 and we could set the data we want to return within the setResult method and close Activity2.  Then automatically the onActivityResult method will be called within Activity1 to hand this information.

We could then determine whether we were looking for the width, or the height within the onActivityResult method with a simple if statement:

if(requestCode == 1){
//set the width variable to the returned data
}else if (requestCode ==2){
//set the height variable to the returned data
}

Hopefully, you somewhat get the idea of the requestCode, so let’s move on to the resultCode parameter. The resultCode, just makes sure everything went smoothly. We define this in Activity2, when we set the result, via the setResult(RESULT_OK, i);. So for our example, we may want to add to it with something like:

if(resultCode == RESULT_OK){
if(requestCode == 1){
//set the width variable to the returned data
}else if (requestCode ==2){
//set the height variable to the returned data
}}

If something goes wrong, the resultCode will not be equal to RESULT_OK, but instead could be something like
RESULT_CANCELED, RESULT_USER, RESULT_ERROR, or whatever we want to set the resultCode as in Activity2.

Lastly, the data parameter will be the actual data that is returned. We can extract the data by getting the “extras” (which we’ll learn about in the next tutorial). Here’s and example:

if(resultCode == RESULT_OK){
if(requestCode == 1){
//set the width variable to the returned data
String width = data.getStringExtra("widthInfo");
}else if (requestCode ==2){
//set the height variable to the returned data
String height = data.getStringExtra("heightInfo");
}}

Now I hope you understand a little bit more about how to pass data between activities using the startActivityForResult, setResult, and onActivityResult methods. In the next tutorial we will learn a bit more about extras, and do a quick review of what we have learned.

Well here is the source for the video tutorial series:


Source Code

The40SeriesActivity.java

package com.mybringback.theworks;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class The40SeriesActivity extends Activity implements OnClickListener {

	Button width, height, calc;
	TextView area;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		width = (Button) findViewById(R.id.button1);
		height = (Button) findViewById(R.id.button2);
		calc = (Button) findViewById(R.id.button3);
		area = (TextView) findViewById(R.id.textView1);

		width.setOnClickListener(this);
		height.setOnClickListener(this);
		calc.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent i = new Intent(this, Numbers.class);
		switch (v.getId()) {
		case R.id.button1:
			// width
			i.putExtra("numbers", "width");

			startActivityForResult(i, 1);
			break;
		case R.id.button2:
			// height
			i.putExtra("numbers", "height");
			startActivityForResult(i, 1);
			break;
		case R.id.button3:
			// calc
			int a = Integer.valueOf(width.getText().toString());
			int b = Integer.valueOf(height.getText().toString());
			area.setText(a*b+" sq ft");
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(data.getExtras().containsKey("widthInfo")){
			width.setText(data.getStringExtra("widthInfo"));

		}
		if(data.getExtras().containsKey("heightInfo")){
			height.setText(data.getStringExtra("heightInfo"));
		}
	}

}

Numbers.java

package com.mybringback.theworks;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Numbers extends Activity implements OnClickListener {
	EditText number;
	Button sendInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.numbers);
		number = (EditText) findViewById(R.id.editText1);
		sendInfo = (Button) findViewById(R.id.button1);
		sendInfo.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String s = number.getText().toString();
		Intent i = getIntent();
		String msg = i.getStringExtra("numbers");
		if (msg.contentEquals("width")) {
			i.putExtra("widthInfo", s);
			setResult(RESULT_OK, i);
			finish();
		}
		if (msg.contentEquals("height")) {
			i.putExtra("heightInfo", s);
			setResult(RESULT_OK, i);
			finish();
		}
	}
}

Resources

Download links: I currently don’t have a zip file for this tutorial. If you have watched the video and working project, please zip it and send it to support@mybringback.com


Course Navigation

Previous Lesson
Next Lesson

Author: trav

I'm just an average guy that love programming.

Share This Post On

1 Comment

  1. Hey Travis!
    I just wanted to say that your tutorials are so great and that they have helped me very much so far!
    Keep it up! You’re doing a phenomenal job!

    Greetings from Serbia.

    Post a Reply

Submit a Comment

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>