• 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 6/21/19

Pass the Player's Score to MainActivity

Log in or subscribe for free to enjoy all this course has to offer!

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 recap!

You now know how to return a result from one Activity to another. This may not seem intuitive, but you will see later that this mechanism is quite powerful.

To make sure you feel comfortable with the content, test yourself on what you've understood with the questions below:

  • To start, which method do you use to receive a user score from GameActivity? 

  • What 2 parameters do you use with the above method? 

  • How do you send a result? 

  • What do you need to do to  onActivityResult  in order to recover the user's score? 

  • What should you verify before you retrieve the score?

In the next chapter, we'll check out how to store preferences.

Example of certificate of achievement
Example of certificate of achievement