• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 12/21/23

Pass the Player's Score to MainActivity

In this chapter, we will have GameActivity communicate the player's score to MainActivity. MainActivity will display the user's most recent score on the main screen.

Receive a Result from another Activity

Recover an Activity Result

We started GameActivity using the startActivity() method. In case you've forgotten, refer to the onClick()  listener for MainActivity 's Play button.

But something's changed: we want to start  GameActivity and we expect to receive a result from it, which will be the user's score. To do this, we need to use startActivityForResult() instead. The method signature is as follows:

public void startActivityForResult(Intent intent, int requestCode)

The first parameter is the same as startActivity() in that it requires an Intent object. The second parameter is more interesting: it makes it possible to specify a "request code." The request code is an identifier that helps us track which Activity we receive a result from. We'll see how this works shortly. 

Starting an Activity with a Result Request

Begin by adding a static variable to define the request code for GameActivity:

private static final int GAME_ACTIVITY_REQUEST_CODE = 42;

The actual value is not important, but it must remain unique to each Activity you launch with startActivityForResult(). Modify onClick()  to launch GameActivity for a result using the new method:

startActivityForResult(gameActivity, GAME_ACTIVITY_REQUEST_CODE);

Send the Result

Open the GameActivity class. Remember when we used the finish()  method to stop the Activity and return to the main screen? That is exactly where we will return the user's score.

To do this, we will create an Intent. In this case, we will use the Intent to pass the user's score back to the first Activity.

To attach a value to an Intent, we must use a  putExtra()  method. These methods have different signatures, depending on the type of value we want to attach. Some examples:

public Intent putExtra(String name, boolean value);
public Intent putExtra(String name, int value);
public Intent putExtra(String name, String value);

As for storing data, we have to provide a "key," because an Intent can contain multiple values. We will define a public class variable to store the name of the key, so that MainActivity can retrieve it. Add the following variable to GameActivity:

public static final String BUNDLE_EXTRA_SCORE = "BUNDLE_EXTRA_SCORE";

Update your code to return the score to the previous Activity:

// onClick ...

Intent intent = new Intent();
intent.putExtra(BUNDLE_EXTRA_SCORE, mScore);
setResult(RESULT_OK, intent);
finish();

// onClick ...

Line-by-line breakdown:

  • 03: Create an empty Intent

  • 04: Attach the player's score to the Intent using BUNDLE_EXTRA_SCORE. MainActivity will use this key to retrieve the score

  • 05: Set the result. RESULT_OK means success, and the Intent object provides additional data (the score, in our case).

  • 06: End the Activity, return to the previous

Result Recovery

Go back to MainActivity. To retrieve the result returned by another Activity, override the onActivityResult()  method. Press CTRL + O, type the first letters of the method ("onAc..."), and press the Enter key. Android Studio generates the following method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

Before you retrieve the score, you need to verify several things:

  1. First, check the requestCode parameter to make sure the result comes from the right place. It must match the value you specified above, in this case, GAME_ACTIVITY_REQUEST_CODE.

  2. Then verify that this Activity has completed successfully by checking the resultCode parameter. Its value must be RESULT_OK, as we specified in the call to setResult() .

  3. Finally, if everything is correct, you can recover the score. To retrieve the score, use getIntExtra().

The corresponding code is:

if (GAME_ACTIVITY_REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
    // Fetch the score from the Intent
    int score = data.getIntExtra(GameActivity.BUNDLE_EXTRA_SCORE, 0);
}

Note the signature of the getIntExtra()  method: the second parameter is used to specify a default value in case the requested value was not set.

Let's Review With a Demo

You can see these steps in the video below:

Let's Recap!

  • Use the  startActivityForResult()  method to open a new Activity and receive a result.

  • Activities receive results in the  onActivityResult()  method. Override it in the main Activity.

  • Using constants comes in handy when the same value must be used in several different places (i.e.,  a request code).

So now you know how to send a result from one Activity to another! This may not seem very intuitive, but you’ll soon see the power behind this mechanism. In the next chapter, we’ll learn how to store the player’s preferences.

Example of certificate of achievement
Example of certificate of achievement