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 earlier post “start Activity” and “ Activity Send Data To Another Activity you have learnt

  • What is Activity
  • How to create an Activity?
  • How one activity starts another activity?
  • How one activity starts another activity and some data to it?

In this article you will learn

How to start an activity for result??

So what does that mean? Sometimes you may want to receive the data back from the activity you have started.

Example : you have a screen(First Activity) which requires user authentication details and you have a button, by clicking on it, a window(Second Activity) appears where user enters the login credentials and system validates the credentials and send back the login status (either successful or failed) to the original screen(First Activity).

So in situations like this, we use startActivityForResult() instead of startActivity().

see the diagram below

Start Acivity For Result

Start Acivity For Result

 

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

in startActivityForResult() we send the request code along with the Intent object.
Request code is nothing but a simple integer that identifies that activity is getting called.
There might be scenario that you activity calls multiple activities at the same time and its possible that not all results return at the same time then how your program will identify which response is getting back from which activity 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 activity which is started, do the desired task and prepare the result and pack it with Intent using setData().

The setResult() method sets a result code ( either RESULT_OK or RESULT_CANCELLED) and the result (an Intent Object) to be returned back to the calling 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 activity started using startActivityForResult() is finished the onActivityResult() method is called automatically.

check the resultcode and requestcode and use intentObject.getData to get the result.

Complete 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 Activity

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

Authenticate 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 Activity For Result

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

Leave a Reply

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