Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

Android Activities — Start An Activity for Result

In our ear­lier post “start Activ­ity” and ” Activ­ity Send Data To Another Activ­ity you have learnt

  • What is Activity
  • How to cre­ate an Activity?
  • How one activ­ity starts another activity?
  • How one activ­ity starts another activ­ity and some data to it?

In this arti­cle you will learn

How to start an activ­ity for result??

So what does that mean? Some­times you may want to receive the data back from the activ­ity you have started.

Exam­ple : you have a screen(First Activ­ity) which requires user authen­ti­ca­tion details and you have a but­ton, by click­ing on it, a window(Second Activ­ity) appears where user enters the login cre­den­tials and sys­tem val­i­dates the cre­den­tials and send back the login sta­tus (either suc­cess­ful or failed) to the orig­i­nal screen(First Activity).

So in sit­u­a­tions like this, we use star­tAc­tiv­i­ty­For­Re­sult() instead of startActivity().

see the dia­gram below

Start Acivity For Result

Start Aciv­ity For Result

 

Intent i = new Intent(this, Authenticate.class);
startActivityForResult(i, requestLoginCode);

in star­tAc­tiv­i­ty­For­Re­sult() we send the request code along with the Intent object.
Request code is noth­ing but a sim­ple inte­ger that iden­ti­fies that activ­ity is get­ting called.
There might be sce­nario that you activ­ity calls mul­ti­ple activ­i­ties at the same time and its pos­si­ble that not all results return at the same time then how your pro­gram will iden­tify which response is get­ting back from which activ­ity and that is why we send request code along with every request.

NOTE: if the request code is -1 then startActivityForResult() works same as startActivity() no result will be returned.
Intent intent = new Intent();
intent.setData(Uri.parse(result));
setResult(RESULT_OK, intent);
finish();

The activ­ity which is started, do the desired task and pre­pare the result and pack it with Intent using set­Data().

The setRe­sult() method sets a result code ( either RESULT_OK or RESULT_CANCELLED) and the result (an Intent Object) to be returned back to the call­ing activity.

public void onActivityResult(int loginCode, int resultCode, Intent i){
    	if(requestLoginCode == loginCode ){
    		if(resultCode==RESULT_OK){
    			Toast.makeText(this, i.getData().toString(), Toast.LENGTH_LONG).show();
    		}else{
    			Toast.makeText(this, i.getData().toString(), Toast.LENGTH_LONG).show();
    		}
    	}
    }

Once the activ­ity started using star­tAc­tiv­i­ty­For­Re­sult() is fin­ished the onAc­tiv­i­tyRe­sult() method is called automatically.

check the result­code and request­code and use intentObject.getData to get the result.

Com­plete Code:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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 = "com.example.login.Authenticate"/>
    </application>

</manifest>

MainAcitivity.Java

Main Activity

Main Activ­ity

package com.example.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	EditText msg ;
	int requestLoginCode = 1;
	public static final String MESSAGE = "com.example.SIMPLE_MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }
    public void startAuthenticate(View v){
    	Intent i = new Intent(this, Authenticate.class);
    	startActivityForResult(i, requestLoginCode);
    }

    public void onActivityResult(int loginCode, int resultCode, Intent i){
    	if(requestLoginCode == loginCode ){
    		if(resultCode==RESULT_OK){
    			Toast.makeText(this, i.getData().toString(), Toast.LENGTH_LONG).show();
    		}else{
    			Toast.makeText(this, i.getData().toString(), Toast.LENGTH_LONG).show();
    		}
    	}
    }

}

activity_main.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Login Page"
        android:textAppearance="?android:attr/textAppearanceLarge" />    

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:layout_gravity="center"
        android:text="Check Login Details"
        android:onClick="startAuthenticate" />

</LinearLayout>

Authenticate.java

Authenticate Activity

Authen­ti­cate Activity

package com.example.login;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Authenticate extends Activity {
	EditText id;
	EditText password;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.authenticate);

		// Toast.makeText(this, "Received Data : " + msg ,
		// Toast.LENGTH_SHORT).show();
	}

	public void validateLogin(View v) {
		String result = "";
		id = (EditText) findViewById(R.id.id);
		password = (EditText) findViewById(R.id.pwd);
		if(id.getText().toString().equals("Sumit")){
			if(password.getText().toString().equals("jain")){
				result = "Login Successful";
			}else{
				result = "Login Failed";
			}
		}else{
			result = "Login Failed";
		}
		Intent intent = new Intent();
		intent.setData(Uri.parse(result));
		setResult(RESULT_OK, intent);
		finish();
	}
}

authenticate.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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Enter ID and Password"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20sp"
        android:layout_gravity="center"
        android:text="Login"
        android:onClick="validateLogin" />

</LinearLayout>

Output:

Start Activity For Result

Start Activ­ity For Result

You may also like...

Leave a Reply

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