Starting and Retrieving data from activities using startActivityForResult() method in Android

August 22, 2012
By

In this article we will create an Android application which demonstrates how to start an activity which returns data on finishing its execution.

The activity that returns the data has to be started by the method startActivityForResult() and the caller activity should override the method onActivityResult(). The called activity can set data using an intent by the method setResult().

This application is developed in Eclipse Classic ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )


1. Create a new Android application project namely “ActivityResultDemo”

New Android Application Project

Figure 1 : New Android Application Project


2. Design application launcher icon

Design Application Launcher icon

Figure 2 : Design Application Launcher icon


3. Create a blank activity

Create a blank Activity

Figure 3 : Create a blank Activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Remove Android support library from this project, if added by the Eclipse

By default Eclipse adds Android Support Library to  an  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>

    <string name="app_name">ActivityResultDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">ActivityResultDemo</string>
    <string name="str_btn_get_result">Get Result</string>
    <string name="str_activity_result">Activity Result</string>
    <string name="str_title_activity_result">Activity Result</string>
    <string name="str_hnt_data">Enter data here </string>

</resources>


7. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_get_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_btn_get_result" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>


8. Create a layout file in res/layout/activity_result_layout.xml


<?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/txt_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/str_hnt_data"
    />

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@android:string/ok"
    />

</LinearLayout>


9. Create an activity class src/in/wptrafficanalyzer/activityresultdemo/ActivityResult.java


package in.wptrafficanalyzer.activityresultdemo;

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.EditText;

public class ActivityResult extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result_layout);

        /** Click event listener for the button OK */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** Getting a reference to the edittext txt_data of the layout activity_result_layout */
                EditText editText = (EditText) findViewById(R.id.txt_data);

                /** Creating an intent object to pass data to the caller activity */
                Intent data = new Intent();

                /** Setting data to the intent object */
                data.putExtra("data",editText.getText().toString());

                /** Setting result , which can be retreived from caller activity in the callback method onActivityResult */
                setResult(RESULT_OK, data);

                /** Exits this activity */
                finish();
            }
        };

        /** Getting a reference to the button available in the layout activity_result_layout */
        Button btnOk = (Button) findViewById(R.id.btn_ok);

        /** Setting click event listener for the button */
        btnOk.setOnClickListener(listener);
    }
}


10. Update the activity class MainActivity in the file src/in/wptrafficanalyzer/activityresultdemo/MainActivity.java


package in.wptrafficanalyzer.activityresultdemo;

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

public class MainActivity extends Activity {

    /** Defining request code */
    private final int REQUEST1 = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Defining a click listener for the button "GetResult" */
        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** Creating an intent object to call the activity ActivityResultDemo */
                Intent i = new Intent("in.wptrafficanalyzer.activityresultdemo.activityresult");

                /** Starting the activity ActivityResultDemo */
                startActivityForResult(i, REQUEST1);
            }
        };

        /** Getting a reference to the "GetResult" button from the layout activity_main */
        Button btn = (Button) findViewById(R.id.btn_get_result);

        /** Setting click listener for the button GetResult */
        btn.setOnClickListener(listener);

    }

    /** A callback method, which is executed when the activity that is called from this activity is finished its execution */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        /**
        * requestCode : an integer code passed to the called activity set by caller activity
        * resultCode : an integer code returned from the called activity
        * data : an intent containing data set by the called activity
        */
        if(requestCode==REQUEST1 && resultCode==RESULT_OK){
            Toast.makeText(getBaseContext(), data.getStringExtra("data"), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


11. Update the file AndroidManifest.xml to include the new activity to this application


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.activityresultdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".ActivityResult"
            android:label="@string/str_title_activity_result" >

            <intent-filter>
                <action android:name="in.wptrafficanalyzer.activityresultdemo.activityresult" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

    </application>

</manifest>


12. Screenshots of the application in execution

MainActivity of the application

Figure 5 : MainActivity of the application

The activity "Activity Result" is opened by clicking "Get Result" button of the MainActivity

Figure 6 : The activity "Activity Result" is opened by clicking "Get Result" button of the MainActivity

Entering data in the ActivityResult

Figure 7 : Entering data in the ActivityResult

The entered data is returned to MainActivity and displayed as Toast Message

Figure 8 : The entered data is returned to MainActivity and displayed as Toast Message


13. Download


14. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner