Advanced use of Intents: Android StartActivityForResult Example

In the previous tutorial  Android Tutorial : Using Intent to move from one activity to another and sending data via putExtra , we saw the use of intent to move from one activity to another, today we will see how to receive a result from the second activity. 
The intent was instructed to call the second activity and through the startActivity method to display it. 
Imagine that our secondary activity has a result to return to the first activity. 

Our objective is to start a second activity that returns result “data” to first activity.
At first create a new Android Application.
  • File >> New >> Android Application
  • Enter Project name: StartActivity
  • Keep other default selections, go Next  until you reach Finish
In your layout folder you must have two Layouts XML files.
The first XML file "activity_main.xml" must contain a Button and the second XML file "second_activity.xml" must contain an EditText and a Button.

  • 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" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/intent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="Click me !" /> </RelativeLayout>


  • res/layout/second_activity.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/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="305dp" android:layout_height="wrap_content" android:text="Submit" /> </LinearLayout>


In the package in src folder you must have two Activities.
The first activity will contain our first UI (activity_main.xml) and the second will contain the second UI (second_activity.xml).
Don't forget to declare all your activities in the AndroidManifest.xml
  • MainActivity.java
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.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
Button btn;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.intent);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
});
}}

  • Second.java
import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Second extends Activity { EditText edit; Button bot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); edit=(EditText)findViewById(R.id.editText1); bot= (Button)findViewById(R.id.button1); } }

Now,we will add a type of code back to our first activity (MainActivity.java) to check for the return of action providing a result.We will call this type return_code with a value of 0 to identify it:
public static final int return_code = 0;
 then we will use the startActivityForResult () to start another activity and expect a return thereof.
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(v == btn) {
    Intent intent = new Intent(MainActivity.this,Second.class);
    startActivityForResult(intent, return_code);
    }
}
});

This method startActivityForResult () takes as parameters the intent and the expected return code. 

The Activity class contains a method named onActivityResult triggered on each return of result from  another activity. This method contains three parameters: the first specifies the code returned (in our example return_code), the second parameter is the returned result (3 Possible values ​​RESULT_CANCELED, RESULT_OK, RESULT_FIRST_USER) and finally the intent to return. 

We will use a different mechanism of the intent called Extras. It is a way to pass Data from one activity to another, the method putExtra  is the source of this mechanism. 
we will now see the code that this method will contain:

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Vérification of the return code

    if(requestCode == return_code) {
        // Vérify if the result equals OK
        if(resultCode == RESULT_OK) {
             String nom = data.getStringExtra("Nom");
            
            Toast.makeText(this, "Your name is : " + nom, Toast.LENGTH_SHORT).show();
        
        } else if (resultCode == RESULT_CANCELED) {
             
            Toast.makeText(this, "Operation canceled", Toast.LENGTH_SHORT).show();
         }
     }
 }

We will then proceed to the second activity (Second.java) to change it.

In the second_activity.xml we have an EditText that allows the user to enter its name and the button to return the information.
At First, we must grab the button and the EditText of our Layout, then in the listener of the onClick event  of the button, we will return a result via the setResult () method that takes two parameters: return code and an Intent if necessary.
 bot.setOnClickListener(new OnClickListener() {
         @Override
        public void onClick(View v) {
        if(edit.getText().length() > 0) {
         Intent intent = new Intent();
 // The name entered in the EditText is added in the intent via putExtra
        intent.putExtra("Nom", edit.getText().toString());
                 // return the result
                setResult(RESULT_OK, intent);
                 // finish this activity
                finish();
             }
        }
    });

Launch the application and click the button "Click me!"If you click on the "Back" button on the phone, the return is equivalent to RESULT_CANCELED and the message "Operation canceled" appears.
However, if you enter a name then you click the "Submit" button, the return code is RESULT_OK and another message appears.

The entire code of MainActivity.java
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.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { Button btn; public static final int return_code = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.intent); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(v == btn) { Intent intent = new Intent(MainActivity.this,Second.class); startActivityForResult(intent,return_code); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Verification of the return code if(requestCode == return_code) {  
// Verify if the result equals OK if(resultCode == RESULT_OK) { String nom = data.getStringExtra("Nom"); Toast.makeText(this, "Your name is : " + nom, Toast.LENGTH_SHORT).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Operation canceled", Toast.LENGTH_SHORT).show(); } } } }

The entire code of Second.java
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; import android.widget.Toast; public class Second extends Activity { EditText edit; Button bot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); edit=(EditText)findViewById(R.id.editText1); bot= (Button)findViewById(R.id.button1); bot.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(edit.getText().length() > 0) { Intent intent = new Intent(); intent.putExtra("Nom", edit.getText().toString()); // return the result setResult(RESULT_OK, intent); // finish this activity finish(); } } }); } }

Commentaires

  1. Tu utilises un Toast avec les données de retour dans onActivityResult, le problème chez moi c'est que onActivityResult est déclenchée avant que la seconde activité est quittée le premier plan. Du coup, si le téléphone rame, on voit pas le toast puisqu'il pop alors que l'activité est en arrière plan.

    RépondreSupprimer

Enregistrer un commentaire

Your comment will be reviewed by moderators

Posts les plus consultés de ce blog

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json

Connexion d'une application Android et une base de données externe Mysql avec web services php Json (opérations CRUD)