Lesson 30. Learn more about onActivityResult. Why requestCode and resultCode are needed
Android Lessons

Lesson 30. Learn more about onActivityResult. Why requestCode and resultCode are needed


In this lesson:

– Understand why requestCode and resultCode are needed in onActivityResult

In the last lesson, we looked at how to call Activity, And how to make it so returned the result. Let’s look at this mechanism in more detail. Let’s create an application that will call two different Activity and get the result from them. As we remember, the result comes in the onActivityResult method. AND requestCode is used to differentiate the results from one another. AND resultCode – allows you to determine whether a call has been successful or not.

Let’s create a project:

Project name: P0301_ActivityResult
Build Target: Android 2.3.3
Application name: ActivityResult
Package name: ru.startandroid.develop.p0301activityresult
Create Activity: MainActivity

Draw a screen in main.xml:



    
    
    
        
        
    

On the screen TextView with text. AND two buttons for color choices font and leveling text in TextView. Pressing the button will cause Activity to select and receive back result.

Let’s start coding in MainActivity.java:

package ru.startandroid.develop.p0301activityresult;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
  
  TextView tvText;
  Button btnColor;
  Button btnAlign;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tvText = (TextView) findViewById(R.id.tvText);
        
        btnColor = (Button) findViewById(R.id.btnColor);
        btnAlign = (Button) findViewById(R.id.btnAlign);
        
        btnColor.setOnClickListener(this);
        btnAlign.setOnClickListener(this);
        
    }

  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    
  }
}

We have identified the screen elements, registered the button handler, and for now we will dwell on this.

Let’s create two other Activity. Let’s start with Activity for of choice colors. Let’s create a layout file color.xml:



    
    
    

We create a class ColorActivity. ColorActivity.java:

package ru.startandroid.develop.p0301activityresult;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ColorActivity extends Activity implements OnClickListener {
  
  Button btnRed;
  Button btnGreen;
  Button btnBlue;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.color);
    
    btnRed = (Button) findViewById(R.id.btnRed);
    btnGreen = (Button) findViewById(R.id.btnGreen);
    btnBlue = (Button) findViewById(R.id.btnBlue);
    
    btnRed.setOnClickListener(this);
    btnGreen.setOnClickListener(this);
    btnBlue.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    Intent intent = new Intent();
    switch (v.getId()) {
    case R.id.btnRed:
      intent.putExtra("color", Color.RED);
      break;
    case R.id.btnGreen:
      intent.putExtra("color", Color.GREEN);
      break;
    case R.id.btnBlue:
      intent.putExtra("color", Color.BLUE);
      break;
    }
    setResult(RESULT_OK, intent);
    finish();
  }
}

As usual, we define the elements, assign a button handler and implement onClick. At onClick we create Intent, then we define, button with which the color was clicked and placed in the Intent object named color and value colors. we put the status RESULT_OK, We specify that the object must be returned intent as a result and we close Activity. We use system constants to value colors.

Similarly, we create an Activity to select the alignment.

Layout file align.xml:



    
    
    

AlignActivity.java:

package ru.startandroid.develop.p0301activityresult;

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

public class AlignActivity extends Activity implements OnClickListener {
  
  Button btnLeft;
  Button btnCenter;
  Button btnRight;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.align);
    
    btnLeft = (Button) findViewById(R.id.btnLeft);
    btnCenter = (Button) findViewById(R.id.btnCenter);
    btnRight = (Button) findViewById(R.id.btnRight);
    
    btnLeft.setOnClickListener(this);
    btnCenter.setOnClickListener(this);
    btnRight.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    Intent intent = new Intent();
    switch (v.getId()) {
    case R.id.btnLeft:
      intent.putExtra("alignment", Gravity.LEFT);
      break;
    case R.id.btnCenter:
      intent.putExtra("alignment", Gravity.CENTER);
      break;
    case R.id.btnRight:
      intent.putExtra("alignment", Gravity.RIGHT);
      break;
    }
    setResult(RESULT_OK, intent);
    finish();
  }
}

Here everything is the same as in ColorActivity. Only we do not work with flowers, but with equalization. Be sure to spell out both Activity in the manifest.

We can now finish the code in MainActivity.java. Let’s add a couple of our own constants in class for convenience:

  final int REQUEST_CODE_COLOR = 1;
  final int REQUEST_CODE_ALIGN = 2;

These constants will be further used as requestCode.

Add the onClick method:

  @Override
  public void onClick(View v) {
    Intent intent;
    switch (v.getId()) {
    case R.id.btnColor:
      intent = new Intent(this, ColorActivity.class);
      startActivityForResult(intent, REQUEST_CODE_COLOR);
      break;
    case R.id.btnAlign:
      intent = new Intent(this, AlignActivity.class);
      startActivityForResult(intent, REQUEST_CODE_ALIGN);
      break;
    }
  }

We determine which button was clicked and send Intent pending return of result. The two calls are different class called Activity and parameter requestCode in the method startActivityForResult. on call ColorActivity we use a constant REQUEST_CODE_COLOR, And when called AlignActivity REQUEST_CODE_ALIGN. We will get this constant back into the result processing method – onActivityResult, And on it we can determine from whose exactly Activity came result.

Let’s implement the onActivityResult method in MainActivity.java:

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // запишем в лог значения requestCode и resultCode
    Log.d("myLogs", "requestCode = " + requestCode + ", resultCode = " + resultCode);
    // если пришло ОК
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
      case REQUEST_CODE_COLOR:
        int color = data.getIntExtra("color", Color.WHITE);
        tvText.setTextColor(color);
        break;
      case REQUEST_CODE_ALIGN:
        int align = data.getIntExtra("alignment", Gravity.LEFT);
        tvText.setGravity(align);
        break;
      }
    // если вернулось не ОК
    } else {
      Toast.makeText(this, "Wrong result", Toast.LENGTH_SHORT).show();
    }
  }

For clarity, we write in log values ​​of variables.

Remember that in ColorActivity and AlignActivity we set the status in the setResult method RESULT_OK when sending the result. means in onActivityResult we should expect this status as a sign of the successful end of the call.

If the call was successful (resultCode = RESULT_OK), then we look at the value requestCode. If it is constant REQUEST_CODE_COLOR, Then we recall that we used this constant in the method startActivityForResultWhen you requested color selection. So we came result this of choice. We take Intent (Data) and we pull out from it the value of the object named color and assign this value color text in TextView. Constant Color.WHITE in the method getIntExtra means the default value. That is, if Intent misses an object named color, Then the method will return to white.

similarly for REQUEST_CODE_ALIGN. We used this constant to request a selection leveling. And if in method onActivityResult parameter requestCode = This constant, then came the answer to the equalization request. And we read that value from Intent and assign it a Gravity attribute for TextView.

if resultCode NOT equal RESULT_OK, So something went wrong. The corresponding message is displayed. This may be the case, for example, if you do not make a selection on the selection screen and press the Back button.

Let’s save everything and launch the application.

click Color

and select, for example, Red

the color has changed

we look at the log:

requestCode = 1, resultCode = -1

requestCode came into the method onActivityResult is 1. True, this is a constant value REQUEST_CODE_COLORThat we used when calling.

resultCode = -1 is the value of the system constant RESULT_OK

That is all right, the answer to the color request came, and its status = RESULT_OK.

Now click Alignment and select Right, get right alignment:

We look at the log:

requestCode = 2, resultCode = -1

requestCode = 2, which is equal to a constant REQUEST_CODE_ALIGN. So the response to the alignment request came.

resultCode = -1, ie RESULT_OK.

Now click Color again

but instead of choosing a color, we press the back button

Our error message was displayed. We look at the logs:

requestCode = 1, resultCode = 0

requestCode = 1 – all right, we asked for color (REQUEST_CODE_COLOR)

resultCode = 0, this value is RESULT_CANCELED, so the call failed

There are no restrictions on the status value in the setResult method. RESULT_OK and RESULT_CANCELED are system common constants. But you can freely use your values ​​if necessary.

So, let’s summarize.

requestCode is a kind of request ID. It seems in method startActivityForResult, And then checked in onActivityResultTo know exactly what the call came from.

resultCode – call status. It seems in method setResult, And checked in onActivityResultTo understand how well the call was successfully completed. If something went wrong during the call, the system constant will return RESULT_CANCELED.

full code MainActivity.java:

package ru.startandroid.develop.p0301activityresult;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

  final int REQUEST_CODE_COLOR = 1;
  final int REQUEST_CODE_ALIGN = 2;

  TextView tvText;
  Button btnColor;
  Button btnAlign;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvText = (TextView) findViewById(R.id.tvText);

    btnColor = (Button) findViewById(R.id.btnColor);
    btnAlign = (Button) findViewById(R.id.btnAlign);

    btnColor.setOnClickListener(this);
    btnAlign.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    Intent intent;
    switch (v.getId()) {
    case R.id.btnColor:
      intent = new Intent(this, ColorActivity.class);
      startActivityForResult(intent, REQUEST_CODE_COLOR);
      break;
    case R.id.btnAlign:
      intent = new Intent(this, AlignActivity.class);
      startActivityForResult(intent, REQUEST_CODE_ALIGN);
      break;
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // запишем в лог значения requestCode и resultCode
    Log.d("myLogs", "requestCode = " + requestCode + ", resultCode = " + resultCode);
    // если пришло ОК
    if (resultCode == RESULT_OK) {
      switch (requestCode) {
      case REQUEST_CODE_COLOR:
        int color = data.getIntExtra("color", Color.WHITE);
        tvText.setTextColor(color);
        break;
      case REQUEST_CODE_ALIGN:
        int align = data.getIntExtra("alignment", Gravity.LEFT);
        tvText.setGravity(align);
        break;
      }
      // если вернулось не ОК
    } else {
      Toast.makeText(this, "Wrong result", Toast.LENGTH_SHORT).show();
    }
  }
}

In the next lesson:

– Learn what a URI is
– call system programs (browser, caller, map)




Discuss in the forum [60 replies]

Leave a Reply

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