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
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
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
'adb' is not recognized as an internal or external command, operable program or batch file.
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
Solution to error: unable to open connection to server due to security error
Comments