How to communicate between two Activities in Android?
An Activity represents the main screen for Android application. An application can have any number of Activities. Intents are message passing mechanisms used in Android. The Android Activity class contains different methods that support Activity communication.
The method startActivity(Intent) is used to invoke one Activity from other Activity. This method accepts an Intent object which specifies the Activity to be started. If the First Activity is expecting some result from Second Activity, a variation of this method is to be used .For example, if you want to start an activity that allows the user to choose a person from the contacts list and when it finishes execution, it will return the selected person. In such cases, the method to be used is startActivityforResult(Intent,int). This method accepts an Intent object and an integer value which is the Request code used to identify the request. When the child finish execution it should call setResult(int) to send data back to First Activity. The argument of setResult(int) method is the Result code which can have constant values like RESULT_OK (operation succeeded),RESULT_CANCELED(operation canceled) etc.. The First Activity should implement onActivityResult(int,int,Intent) method to receive data send by second Activity, where first argument is the Request code,second is Result code and third is the Intent object. Finally the Second Activity should call finish() method to give control back to First Activity. The methods to be implemented are
First Activity startActivityForResult(Intent,int) onActivityResult(int,int,Intent)
Second Activity setResult(int) finish()
Sample code for Activity Communication in Android
FirstActivity.java
package com.samples;
import android.app.Activity;
import android.content.ActivityNotFoundException;
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.Toast;
public class FirstActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Button name = (Button)findViewById(R.id.Select);
name.setOnClickListener(new OnClickListener() {
public void onClick(View v){
Intent myIntent = new Intent();
myIntent.setClass(FirstActivity.this,SecondActivity.class);
startActivityForResult(myIntent,1);
}
});
} catch (ActivityNotFoundException anfe) {
Log.e("onCreate", " Activity Not Found", anfe);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch(requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra("Selected");
Toast.makeText(this, "You have selected : " + " " + name, Toast.LENGTH_LONG).show();
break;
}
}
}
}
SecondActivity.java
package com.samples;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class SecondActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Names));
getListView().setTextFilterEnabled(true);
}
static final String[] Names = new String[]{
"JAVA",
"Python",
"Perl",
"LISP",
"COBOL",
"JSF",
"JSTL",
"Ruby",
"PHP"
};
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String name = o.toString();
Intent newIntent = new Intent();
newIntent.putExtra("Selected",name);
setResult(RESULT_OK,newIntent);
finish();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:text="@string/Select"
android:id="@+id/Select"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Please select an Option</string>
<string name="app_name">Activity Communication</string>
<string name="Select">Names</string>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.samples"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity">
</activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
Output will be as shown below
Very good article.Realy I am very benefited by this example. Thanks for your contribution.