Pages - Menu

Monday 22 October 2012

Invoking An Activity For Result

An android application contains number of activities. It is essential to establish the communication between  these activities. In android an activity call another one by means of an intent filter. The intent filter is a sub tag of the Activity tag in androidmanifest.xml file.
In an android application an activity can be invoked in any of the following ways.

(1) Invoking an activity using the startActivity method and
(2) Invoking an activity for result using the startActivityForResult method 
In the first method an activity calls another activity without expecting any result from it. This is achieved by using just the startActivity() method. 
In the second method the calling activity expects a result from the called activity by invoking it using the 
startActivityForResult() method.
                        
The startActivityForResult method contains two arguments, first one is the intent object and second one is the request_code. The argument request_code is used for identifying the calling activity. The calling activity sends a request_code to the called activity and the called activity returns the result with the same request code. This will help to identify the exact result from the number of activities responding to the calling activity at same time. The request_code is an integer value. If we use -1 for request_code then the startingActivityForResult() will be same as the startActivity()
Syntax for starting an activity for result as follows.
                                 startActivityForResult(new Intent(""), request_code);

E.g
              startActivityForResult("com.codeglympse.SecondActivity", request_code );
In order to get the result for the called activity, the calling activity must contain the onActivityResult  method.
                          public void onActivityResult(int request_code, int result_code, Intent data)
                            {     
                       
                            }
 Here three arguments are present. The first one is the request_code used for identifying the exact activity responding to the request, second one is the result_code used for the identifying weather it is RESULT_OK or RESULT_CANCELLED and the final one is the Intent object which contains the attached data from the called activity.
The sending activity sends the result by means of the intent object with the help of setData method.
                           intent_obj.setData(Uri.parse(passing_data));
The data is returned to the calling activity by using the method setResult. The setResult method contains two arguments RESULT_OK or RESULT_CANCELLED and the data 0bject. 
                          setResult(RESULT_OK, data_obj);               

For more details about the startingActivityForResult, consider the following example.
Create a new android project with name ActivityForResult. In this example we call the second activity SecondActivity from the main activity. For that, we place a button in the first activity xml file as shown bellow.

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="vertical" >

 <TextView
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:text="@string/hello" />

  <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      ndroid:layout_height="wrap_content"
      android:text="GET RESULT" />
    </LinearLayout>          
              
Now create a second activity layout second_layout.xml and a SecondActivity.java class. Place a EditText and a submit button in the second_layout.xml as follows.




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

  <EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
    <requestFocus />
    </EditText>

  <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="submit" />
</LinearLayout>

In order to receive the result, the calling activity must contain the method onActivityResult()
                      public void onActivityResult(int request_code, int resultcode, Intent data)
                               {

                               }

The ActivityForResultActivity.java file is shown bellow.

package com.codeglumpse;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ActivityForResultActivity extends Activity {
Button bn;
int requestcode=1;
 /** Called when the activity is first created. */
    @Override
  public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 bn = (Button) findViewById(R.id.button1);
 bn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent("com.codeglympse.SecondActivity") ;
startActivityForResult(i,requestcode);
}
});
  }

public void onActivityResult(int request_code, int resultcode, Intent data)
{
if(request_code==requestcode)
{
if(resultcode==RESULT_OK)
{
Toast.makeText(this, "Welcome "+data.getData().toString(), Toast.LENGTH_SHORT).show();
}
}
}
}


The SecondActivity.java is as follows.
package com.codeglumpse;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Button bn = (Button) findViewById(R.id.submit);
bn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent data  = new Intent();
EditText tx = (EditText) findViewById(R.id.editText1);
data.setData(Uri.parse(tx.getText().toString()));
setResult(RESULT_OK,data);
finish();
}
});
}
}


Here is the editing done in the AndroidManifest.xml file.


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.codeglumpse"
   android:versionCode="1"
   android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <application
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name" >
     <activity
     android:label="@string/app_name"
     android:name=".ActivityForResultActivity" >
     <intent-filter >
     <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    <activity
    android:label="@string/second" 
    android:name=".SecondActivity" >
    <intent-filter >
    <action android:name="com.codeglympse.SecondActivity" />
    <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    </activity>
    </application>
    </manifest>


Here is the output of the project























No comments:

Post a Comment