Android: explicit intents

The Intent class is used in Android programs to communicate between various types of processes. We’ll consider the case where an Intent is used to start one Activity from within another Activity, and another Intent is used to send data back from the second Activity to the first.

Create a new project in Eclipse as described in our previous post. Add a main Activity called StartActivity which is displayed when the app starts. The layout of this Activity consists of:

  • a Button with ID getTextButton that has the caption “Get text”
  • a TextView with the text “You entered:”
  • another TextView, with ID enteredText, initially blank

When the button is pressed, a second Activity, called GetTextActivity, will start that will have the following layout:

  • a horizontal LinearLayout (we’ll get to these in a later post) which contains:
    • a TextView with the text “Enter your text:”
    • an EditText, with ID userText, into which the user can type some text
  • a Button with ID sendTextButton and caption “Send text”

All of this can be set up using Eclipse’s graphical UI editor, which will create the corresponding code in the various XML files automatically.

The idea is that the user presses the “Get text” button to show the second Activity, then types some text into the EditText box and presses the “Send text” button. This returns the app to the first Activity, which displays the entered text in the enteredText TextView.

In order to do this, we need to use one Intent to start GetTextActivity from within StartActivity and another Intent to send the entered text back from GetTextActivity to StartActivity.

Here’s the code for StartActivity:

package com.example.ex02explicitintent;

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

public class StartActivity extends Activity {

	static final int GET_TEXT_ACTIVITY = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start);
	}

	public void onClickGetText(View view) {
		Intent getTextIntent = new Intent(getBaseContext(), GetTextActivity.class);
		startActivityForResult(getTextIntent, GET_TEXT_ACTIVITY);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK)
		{
			return;
		}
		if (requestCode == GET_TEXT_ACTIVITY)
		{
			String userText = data.getStringExtra(getString(R.string.userTextTag));
			TextView enteredText = (TextView) findViewById(R.id.enteredTextView);
			enteredText.setText(userText);
		}
	}
}

The onClickGetText() (lines 19-22) method is the event handler for getTextButton. It illustrates how to create an explicit Intent, which is an Intent that creates a specifically named Activity. (There are also implicit Intents). Here we want a GetTextActivity to start in response to the button press, so we name this class explicitly in the Intent constructor.

We then start the Activity by calling startActivityForResult(). The ‘ForResult’ in the method name means that we expect the Activity to return a result after it finishes running. If we just wanted to start an Activity with no return data, we can call startActivity().

The startActivityForResult() method takes the Intent as its first argument, and an int label (defined on line 11) as its second argument. We need a label because if we start more than one Activity that will return data, they all call the same method onActivityResult() when they return, so we need to tag each Activity so we know which one is returning the data. (OK, since we’re creating only one Activity here, technically we don’t need a tag, but in the more general case we will so it’s a good idea to get into the habit of adding the tag.)

Before we see how to handle the returned result, we need to look at the other Activity to see how it sends back its data. Here’s the code for GetTextActivity:

package com.example.ex02explicitintent;

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

public class GetTextActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_get_text);
	}

	public void onClickSendText(View view) {
		EditText userEditText = (EditText)findViewById(R.id.userText);
		String userText = userEditText.getText().toString();
		Intent userIntent = new Intent();
		userIntent.putExtra(getString(R.string.userTextTag), userText);
		setResult(RESULT_OK, userIntent);
		finish();
	}
}

This Activity contains only the event handler for the sendText button. We retrieve the EditText control by using its ID and extract the text from it (lines 18-19). Then we create a new Intent. This time, we’re not starting a new Activity, so the Intent doesn’t have an Activity specified in its constructor. What we do want to do is send back userText to StartActivity. We can attach data to an Intent by adding Extras to it. Each Extra consists of a key (which is a String) and a corresponding value, which here is just userText. Note that we’ve defined the key as a string resource (by adding it to the strings.xml file) and retrieved it on line 21 using getString() which looks up a string using its ID. We do it this way since we’ll need to use the same key back in StartActivity to extract the Extra from the Intent.

After adding userText to the Intent, we use setResult() on line 22 to attach the Intent to the GetTextActivity. The first argument to setResult() is a result code to indicate the status of GetTextActivity when it finishes. This result code is also sent back to StartActivity and can be checked to determine what to do with the returned Intent.

Finally, we call finish() to shut down GetTextActivity and send the Intent back to StartActivity.

Returning to the code above for StartActivity, the onActivityResult() method is called when GetTextActivity finishes. The arguments in this method are:

  • requestCode: the tag that was attached to the Activity that has just finished
  • resultCode: the result code that was set in the Activity that has just finished
  • data: the Intent returned by the other Activity

On line 26, we check the resultCode to ensure that GetTextActivity finished properly. Then we check the requestCode to ensure that it really is GetTextActivity that is calling onActivityResult(). If so, then we extract the userText from the Intent, again using the string resource for the tag. Then we retrieve the enteredText TextView control and set its text to userText.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Trackbacks

  • By Android: implicit intents | Programming tutorials on February 20, 2014 at 1:14 PM

    […] seen how to use an explicit intent to start a second Activity from within an existing Activity by giving the name of the second […]

  • […] notification to restart a closed app when clicked, we need to provide some more code. We can use an explicit Intent to restart the app in the way we did earlier, so we define mainIntent on line 6 to do this. Since […]

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: