Android Activity Call and Wait

An Activity is a core part of any Android Application. It is usually the user interface that the application user interacts with. Typically the Android application will consist of one or more activities. In this blog post we shall discuss how to launch an activity with the consideration that we would like to get back some data from the activity that is invoked. In other words, we will have a Parent Activity that will launch an Activity and wait for the result of that Activity.

To repeat, we will do the following:

1)      A main Activity that is launched at startup. Let us call this Activity A.

2)      Activity A will launch another Activity B and pass it some data.

3)      Activity B will work on that data, change it a bit and then finish itself by sending back the result to the calling Activity i.e. Activity A.

4)      Finally, Activity A will display the changed values that were returned to it by Activity B.

An example where you would utilize this pattern would be: From a Parent Activity, launch an activity that presents the user with certain choices. The choices as selected are then returned back to the Parent.

Let us discuss the implementation of this program flow now. We will assume that you are familiar with creating Android Projects. The focus will be on the topic of this article.

Step 1: Create an Android Project named ActivityFlow and name the main Activity as ParentActivity.

Step 2: The Android Manifest XML file is shown below. It consists of two activities, the main Activity i.e. ParentActivity and the ChildActivity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.xoriant.android.blog"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ParentActivity"
                  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=".ChildActivity"
                  android:label="@string/app_name"/>
    </application>
</manifest>

Step 3: The Parent Activity Layout XML (main.xml) is shown below:

<?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/val1"
    />
    <EditText android:text="" android:id="@+id/txtVal1" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/val2"
    />

<EditText android:text="" android:id="@+id/txtVal2" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText>
<Button android:text="@string/lblBtnActivityStart" android:id="@+id/btnLaunchChildActivity" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

It consists of two EditText controls that will allow the user to type in values that they want. We will be sending these values to the Child Activity that will be launched when you click the Start Child Activity button as shown below:



Step 4: ParentActivity.java. Here we will demonstrate two methods, namely onCreate and onActivityResult:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartActivity = (Button)findViewById(R.id.btnLaunchChildActivity);
        txtVal1 = (EditText)findViewById(R.id.txtVal1);
        txtVal2= (EditText)findViewById(R.id.txtVal2);
        btnStartActivity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(),ChildActivity.class);
				intent.putExtra("Val1", txtVal1.getText().toString());
				intent.putExtra("Val2", txtVal2.getText().toString());
				startActivityForResult(intent, CHILD_ACTIVITY_CODE );

			}
		});
    }

The first few lines are standard where the main.xml layout is rendered in the Activity View. The Child Activity is launched via the Click Listener that we have registered on the Start Child Activity. Notice that we use the Intent to add additional data to it via the putExtra method. Here we are setting the two values that the user enters in the activity screen. Also notice that we have launched the Intent for the Child Activity via the startActivityForResult method. This method provides an additional int value which will be used later on in the code shown below to display back the values that the Child Activity would set:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CHILD_ACTIVITY_CODE && resultCode == RESULT_OK) {
			//Display the modified values
            txtVal1.setText(data.getExtras().getString("Val1"));
            txtVal2.setText(data.getExtras().getString("Val2"));
        }
        super.onActivityResult(requestCode, resultCode, data);
	}

In the above code, we first check if the requestCode is the same that we launched the Activity with and if the result is good (RESULT_OK). If yes, we simply extract out the data from the extra information that is passed into the Intent and display it in the EditText fields.

Step 5: Finally, we come to ChildActivity.java and its associated layout file (childactivity.xml). The Layout file shown below is nearly identical to the main layout file:

<?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/val1"
    />
    <EditText android:text="" android:id="@+id/txtVal1" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText>
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/val2"
    />

<EditText android:text="" android:id="@+id/txtVal2" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText>
<Button android:text="@string/lblBtnActivityEnd" android:id="@+id/btnEndChildActivity" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

We will discuss below the OnCreate method of the ChildActivity.java file.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.childactivity);
        btnEndActivity = (Button)findViewById(R.id.btnEndChildActivity);
        txtVal1 = (EditText)findViewById(R.id.txtVal1);
        txtVal2= (EditText)findViewById(R.id.txtVal2);

        //Read the values passed to this Child Activity

        txtVal1.setText(getIntent().getStringExtra("Val1"));
        txtVal2.setText(getIntent().getStringExtra("Val2"));

        btnEndActivity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = getIntent();
				intent.putExtra("Val1", txtVal1.getText().toString());
				intent.putExtra("Val2", txtVal2.getText().toString());
                setResult(RESULT_OK, intent);
                finish();
			}
		});
    }

Let us go through the code in brief.

  • We first get a handle to the Controls present in the Activity View.
  • Next, we display the existing values that were passed from the Parent Activity by extracting the values from the Intent.
  • Finally in the onclick handler of the End Child Activity button, we set the new values back into the Intent, we invoke setResult with RESULT_OK and the additional data i.e. intent. Finally we end the Activity explicitly by calling the finish() method.

Please note that we have omitted certain parts of the code and the associated strings.xml file for sake of brevity.

For more information on Activities, please refer to the Android Developer Guide.

 

 

One thought on “Android Activity Call and Wait

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s