Intent in Android to call one activity from another activity.

By: Ashley Printer Friendly Format    

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>






Ask a Question



Most Viewed Articles (in Android )

Latest Articles (in Android)

Comment on this tutorial

Ask a Question

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. Great! Thanks a lot.
View Tutorial          By: Michael at 2011-12-27 01:16:25

2. hou to cal activity of one project into another pr
View Tutorial          By: manjunath at 2012-01-02 15:45:32

3. great job
i seriously feel that this site i

View Tutorial          By: saurabh at 2012-01-17 05:28:32

4. I'm trying to learn navigating between activities.
View Tutorial          By: Ben at 2012-01-17 23:42:38

5. Hello
I installed Android in eclipse...only

View Tutorial          By: amit kumar at 2012-01-19 11:04:55

6. Thank you. I found this very helpful.
View Tutorial          By: tavella at 2014-09-26 01:04:13

7. no
View Tutorial          By: mc at 2015-11-19 12:43:31

8.
View Tutorial          By: at 2017-06-25 01:35:41

9. Larryhaw
View Tutorial          By: Larryhaw at 2017-07-29 11:55:51

10. Lorenedib
View Tutorial          By: Lorenedib at 2017-08-04 04:44:59

11. Allenmypon
View Tutorial          By: Allenmypon at 2017-08-07 17:46:58

12. Shawncob
View Tutorial          By: Shawncob at 2017-08-27 21:28:35