Intent in Android to call one activity from another activity.

By: Ashley Emailed: 1654 times Printed: 2121 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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>





Android Home | All Android Tutorials | Latest Android Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(5)


1. View Comment

hou to cal activity of one project into another project['m not asking in same project]

View Tutorial          By: manjunath at 2012-01-02 15:45:32
2. View Comment

great job
i seriously feel that this site is the best site to learn android
carry on


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

I'm trying to learn navigating between activities. My question is, when you create a new activity(I'm using Eclipse) in an existing project, how do you go about adding the xml file for the layout for it?

View Tutorial          By: Ben at 2012-01-17 23:42:38
4. View Comment

Hello
I installed Android in eclipse...only showing sdk manager not showing AVD manager...what should i have to do...


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

Thank you. I found this very helpful.

View Tutorial          By: tavella at 2014-09-26 01:04:13

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashley
Is autodiscover CNAME a must in Office 365
Directory Synchronization tool in Office 365
Configure Outlook Manually for Office 365
Review: Ruggear - The world's most Rugged Phone in Singapore
Solution to error: unable to open connection to server due to security error
Making your Alias email as 'Send As' in Office 365
Steps to Create Shared Mailbox in office 365
xxxx cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
The user's Outlook Live mailbox is full.
Outlook Live couldn't connect to the IMAP server.
The user's mailbox has already been migrated.
An Outlook Live mailbox wasn't found for the user.
Outlook Live couldn't sign in to the user account on the IMAP messaging system.
Android Send SMS and Make a phone call in Android Application
Android Preferences - Using Preferences in Android Tutorial

More Tutorials in Android
Getting Started with Android
Solution to error: unable to open connection to server due to security error
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
Android Emulator
Intent in Android to call one activity from another activity.
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android

More Latest News
Most Viewed Articles (in Android )
Progress bar and downloading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
GridView sample program in Android
Intent in Android to call one activity from another activity.
Android Send SMS and Make a phone call in Android Application
Solution to error: unable to open connection to server due to security error
Date and Time sample program in Android
Reading a file sample program in Android
AlertDialog sample program in Android
Error generating R.java from manifest
ArrayAdapter sample program in Android
Spinner sample program in Android
Android Preferences - Using Preferences in Android Tutorial
Getting Started with Android
Animation sample program in Android
Most Emailed Articles (in Android)
Getting Started with Android
Intent in Android to call one activity from another activity.
Error generating R.java from manifest
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
AlertDialog sample program in Android
Spinner sample program in Android
Date and Time sample program in Android
Reading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
GridView sample program in Android
Gallery sample program in Android