Creating SubActivity, Passing data to SubActivity and Retrieving data from SubActivity

In this tutorial, I am going to explain about the subactivity in Android.

The basic thing that I am going to explain in this tutorial is,

From a main activity calling another activity or subActivity, passing data to the subActivity using startActivityForResult() and retrieving information from the subActivity using the callback function called onActivityResult().

The UI contains TextView, EditText and a button. Whatever we type in the editText will appear in the next activity.

First we will pass data from main Activity to subActivity using Bundle. We can put all primitive data types and String to bundle. Bundle will take data as Key/Value pair. Then we will put this bundle into the Intent using intent.putExtras(bundle). We will pass this intent object to startActivityForResult() with a REQUEST_CODE.

In subActivity, we will retreive the data using

Bundle bundle = this.getIntent().getExtras();

Then by passing the desired key, we will get the values using get method.

Seems so easy, right ??

The final part is retrieving information from subActivity :: This is done through the method called setResult()

Same like in mainActivity, whatever we want to retrieve, will put in bundle, then in intent. Pass this intent to setResult() with a RESULT_CODE. In mainActivity we will receive the information in onActivityResult().

The source code of the program is,

Code for mainActivity,

public class PassingData extends Activity {

EditText text;
Button next;
String name;
TextView statText, retData;
static int REQUEST_CODE = 1;

public void onCreate(Bundle savedInstanceState) {

statText = (TextView) findViewById(;
retData = (TextView) findViewById(;

text = (EditText) findViewById(;
next = (Button) findViewById(;
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
name = text.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("name", name);
Intent intent = new Intent(PassingData.this, RetrievePage.class);
startActivityForResult(intent, REQUEST_CODE);

public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Req code : "+requestCode, "Req code : "+requestCode);
Log.i("Result code : "+resultCode, "Result code : "+resultCode);

Code for subActivity,

public class RetrievePage extends Activity {

String retrievedData;
TextView viewData;
static int RESULTCODE = 2;
public void onCreate(Bundle savedInstanceState) {
Bundle bundle = this.getIntent().getExtras();
if(bundle != null) {
retrievedData = bundle.getString("name");
viewData = (TextView) findViewById(;
Bundle b = new Bundle();
b.putString("Value", retrievedData);
Intent intent = new Intent();
setResult(RESULTCODE, intent);


Popular posts from this blog

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture

AlarmManager and Notification in Android