Android Intents Example

0

In this article, I am going to show you how an activity can communicate with another activity and get a response in return.

We will be making use of android’s intent object as the messaging object.

Let’s start with an example.

Our example consists of two activities. If you are new to activities, remember for now, that they represent a single screen in an app.

The first activity has a text field and a button. In the text field, you enter the text that you want send it to the second activity. After entering the text, click on the ‘Send to Activity2’ button to start the second activity. The text entered in the first activity will show up in the second activity.

Next, you may enter some response in the second activity that you want to send it back to the first activity and then click on the custom back button to navigate back to the first activity. Moment the control reaches the first activity, the response will be shown in there.

First Activity’s Layout

The first activity has a text field and a button.

activity1_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/messageToActivity2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/message" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/sendToActivity2Btn"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/send" />

</LinearLayout>

Second Activity’s Layout

The second activity has a view field and a text field. The view field will display the text from the first activity. In the edit field, you may type-in some response that you want to send it back to the first activity.

activity2_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/messageFromActivity1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/replyToActivity1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/reply" >

        <requestFocus />
    </EditText>
</LinearLayout>

First Activity Class

You can start an Activity by passing an Intent to startActivity(). The Intent sent should be an explicit one which knows the activity to start and carries the data that the second activity is interested in.
If you want to receive a result from the activity on its finish, call startActivityForResult(intent, 1) instead of startActivity().

Once the second activity is done with its execution, it will put the response back into an intent object and call on finish() to return back to the first activity. The first activity will receive the response as a separate intent object in your activity’s onActivityResult() callback.

The second parameter in call to startActivityForResult(intent, 1) identifies the call. The result will be obtained from getIntent() using the extra value as the key.

Let’s go through each step in Activity1.

  1. Call setContentView(R.layout.activity1_layout) to set the layout
  2. Find the ‘Send to Activity2’ button. We need this to set the listener.
  3. Find the text field. We will be using this to get the text that needs to be sent to the second activity
  4. Set the buttons listener. Create the Intent object. Put the message to be sent against the extra value “message” which will act as the key.
  5. Call on startActivityForResult(intent, 1) to start the second activity
  6. Override onActivityResult callback to react to the result sent from the second activity
  7. The response will fetched from the intent using the extra value “reply” and then shown on the screen using Toast.makeText

Activity1:

package com.javarticles.android;

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

public class Activity1 extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity1_layout);		
		Button sendToActivity2Button = (Button) findViewById(R.id.sendToActivity2Btn);
		final EditText messageField = (EditText) findViewById(R.id.messageToActivity2);
		sendToActivity2Button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Activity1.this, Activity2.class);								
				intent.putExtra("message", messageField.getText().toString());
				startActivityForResult(intent, 1);
			}});
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("activity result", "Got " + resultCode);
		if (requestCode == 1) {
			String reply = data.getStringExtra("reply");
			Toast.makeText(this, "Reply from Activity2: " + reply, Toast.LENGTH_LONG).show();
		}
	}
}

Second Activity Class

Let’s go through the code in Activity2 class.

  1. We get the intent object using getIntent(). We will read the message from the Intent object using intent.getStringExtra("message").
  2. The message retrieved is set to the text field. If we want to send any response, we need to enter some text in the ‘Reply to Activity1’ text box and then click on the back button.
  3. The reply is put into an intent object against extra value “reply”. Method setResult(RESULT_OK, reply) is called to set the result.
  4. Finally, finish() is called to return back to Activity1.

Activity2:

package com.javarticles.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

public class Activity2 extends Activity {
	private EditText replyToActivity1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set the layout of the Activity
		setContentView(R.layout.activity2_layout);
		replyToActivity1 = (EditText) findViewById(R.id.replyToActivity1);

		// Get the intent that we have passed from Activity1
		Intent intent = getIntent();

		// Get the message
		String message = intent.getStringExtra("message");
		TextView messageField = (TextView) findViewById(R.id.messageFromActivity1);
		messageField.setText("Message from Activity1: " + message);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.back:
			//Send the response back to Activity1
			Intent reply = getIntent();
			reply.putExtra("reply", replyToActivity1.getText().toString());
			setResult(RESULT_OK, reply);
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
}

In the first activity page, you will see a text field and a button.

First Activity

First Activity

Enter some text and click on ‘Send to Activity2’ to send the text to the second activity.

Enter some text to send to the second activity

Enter some text to send to the second activity

In the second activity, you can see the text sent from the first activity.

Second Activity

Second Activity

Enter the response in ‘Reply to Activity2’ and click on the back button to return to the first activity.

Enter response to the first activity call

Enter response to the first activity call

The back button will take us to the first activity page and the response will be shown there.

Response from Second Activity

Response from Second Activity

Download the Source Code

This was an example about Android Intents. You can download the source code here: simpleIntentExample.zip

Share.

Comments are closed.