Programming Tutorials

Intent in Android to call one activity from another activity.

By: Ashley in Android Tutorials on 2011-07-17  

This sample android program shows you how to call an activity from another activity in Android. In this program the concept of Intent is demonstrated. Using Intent the control can be passed between different activity back and fourth. Bundles can be used to pass data from one activity to another activity. In this sample program, two activities are used. Activity1.java and Activity2.java are shown below. Some data is passed between activities to explain the concept. 

The Activity1.java file is as follows:

package com.javasamples.intent1;

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

public class Activity1 extends Activity {
	TextView label1;
	TextView label1Returned;
	Button btnCallActivity2;
	private final int IPC_ID = 1122;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.main);
			label1 = (TextView) findViewById(R.id.label1);
			label1Returned = (TextView) findViewById(R.id.label1Returned);
			btnCallActivity2 = (Button) findViewById(R.id.btnCallActivity2);
			btnCallActivity2.setOnClickListener(new Clicker1());
			label1.setText("Activity1   (sending...) \n\n"
					+ "myString1:  Hello Android" + "\n"
					+ "myDouble1:  3.141592     " + "\n"
					+ "myIntArray: {1 2 3} ");
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}// onCreate
	private class Clicker1 implements OnClickListener {
		public void onClick(View v) {
			try {
				Intent myIntentA1A2 = new Intent(Activity1.this,
						Activity2.class);

				Bundle myData = new Bundle();
				myData.putString("myString1", "Hello Android");
				myData.putDouble("myDouble1", 3.141592);
				int[] myLittleArray = { 1, 2, 3 };
				myData.putIntArray("myIntArray1", myLittleArray);

				myIntentA1A2.putExtras(myData);

				startActivityForResult(myIntentA1A2,IPC_ID);
			} catch (Exception e) {
				Toast.makeText(getBaseContext(), e.getMessage(),
						Toast.LENGTH_LONG).show();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			switch (requestCode) {
			case IPC_ID: {
				if (resultCode == Activity.RESULT_OK) {

					Bundle myReturnedData = data.getExtras();
					String myReturnedString1 = myReturnedData
							.getString("myReturnedString1");
					Double myReturnedDouble1 = myReturnedData
							.getDouble("myReturnedDouble1");
					String myReturnedString2 = myReturnedData
							.getString("myCurrentTime");

					label1Returned.setText(myReturnedString1 + "\n"
							+ Double.toString(myReturnedDouble1) + "\n"
							+ myReturnedString2);
				} else {

					label1.setText("Selection CANCELLED!");
				}
				break;
			}
			}
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)
					.show();
		}
	}

}

The Activity2.java file is as follows:

package com.javasamples.intent1;

import java.util.Date;

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

public class Activity2 extends Activity {
    TextView label2;
    Button   btnCallActivity1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        label2 = (TextView)findViewById(R.id.label2);
        btnCallActivity1 = (Button)findViewById(R.id.btnCallActivity1);
        btnCallActivity1.setOnClickListener(new Clicker1());
        Intent myLocalIntent = getIntent();
        Bundle myBundle = myLocalIntent.getExtras();


        String str1 = myBundle.getString("myString1");
        double dob1 = myBundle.getDouble("myDouble1");
        int[]  arr1 = myBundle.getIntArray("myIntArray1");
        

        String strArr  = "{ ";
        int sumIntValues = 0;
        for (int i=0; i<arr1.length; i++) {
        	sumIntValues += arr1[i];
        	strArr += Integer.toString( arr1[i] ) + " ";
        }
        strArr += " }";


        label2.setText("Activity2   (receiving...) \n\n" +
        		       "myString1:   " + str1 + "\n" + 
        		       "myDouble1:   " + Double.toString(dob1) + "\n" + 
        		       "myIntArray1: " + strArr);
                
  
        double someNumber = sumIntValues + dob1;
        myBundle.putString("myReturnedString1", "Adios Android");
        myBundle.putDouble("myReturnedDouble1", someNumber);
        myBundle.putString("myCurrentTime", new Date().toLocaleString() );
        myLocalIntent.putExtras(myBundle);

        setResult(Activity.RESULT_OK, myLocalIntent);
        
    }//onCreate
    
    private class Clicker1 implements OnClickListener {
		public void onClick(View v) {
			finish();			
		} 	
    }

}



The output of this program will be as shown in the android emulator below.

When you click the 'Call Activity2' button the activity 2 will be called and the screen will look as below.

For this intent demo program, there are two activities and hence there will be two resource files to represent the above two screen shots.
The main.xml file in your res/layout folder is as follows for the activity 1:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	android:id="@+id/linLayout"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:background="#ffccffff"
	android:orientation="vertical"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<TextView
		android:id="@+id/caption1"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="#ffff3300"
		android:padding="4sp"
		android:text=" Activity1 "
		android:textSize="20px"
		android:textStyle="bold"
		android:textColor="#ff000000">
	</TextView>
	<TextView
		android:id="@+id/widget107"
		android:layout_width="fill_parent"
		android:layout_height="2sp">
	</TextView>
	<TextView
		android:id="@+id/label1"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="#ff0033cc"
		android:text="Data to be sent to SubActivity:"
		android:textStyle="bold">
	</TextView>
	<Button
		android:id="@+id/btnCallActivity2"
		android:layout_width="149px"
		android:layout_height="wrap_content"
		android:padding="6sp"
		android:text="Call  Activity2"
		android:textStyle="bold">
	</Button>
	<TextView
		android:id="@+id/label1Returned"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:background="#ff0033cc"
		android:text=" Data returned by Activity2"
		android:textStyle="bold">
	</TextView>
</LinearLayout>

The main2.xml file as below for the activity 2.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffffcc"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffff9900"
android:padding="4sp"
android:text=" Activity2"
android:textSize="20px"
android:textStyle="bold"
>
</TextView>
<TextView
android:id="@+id/widget107"
android:layout_width="fill_parent"
android:layout_height="2sp"
>
</TextView>
<TextView
android:id="@+id/label2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ff0033cc"
android:text="Data Received from Activity1 ..."
android:textStyle="bold"
>
</TextView>
<Button
android:id="@+id/btnCallActivity1"
android:layout_width="149px"
android:layout_height="wrap_content"
android:padding="6sp"
android:text="CallBack  Activity1"
android:textStyle="bold"
>
</Button>
</LinearLayout>









Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Android )

Latest Articles (in Android)

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error

Related Tutorials

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error