Intent parameters

It’s very useful to be able to pass parameters when you start a new activity. These are stored as “extra data” in the Intent object. A good example of this is having a menu for an easy, medium, or difficult game. In all cases, you want to move on to the GameActivity, but you’d like to let GameActivity know which difficulty level was selected.

In this menu layout, I gave these buttons the IDs

  • @+id/easyB
  • @+id/mediumB
  • @+id/difficultB

In the corresponding activity, we can create a method to distinguish between them using getId(), and then use putExtra() in the intent to send an integer code. Bind the following method to the onClick properties of each of the buttons.

    public void selectLevel(View v) {
        Intent i = new Intent(this, GameActivity.class);
        switch(v.getId()) {
            case R.id.easyB:
                i.putExtra(GAME_LEVEL_KEY, 1);
                break;
            case R.id.mediumB:
                i.putExtra(GAME_LEVEL_KEY, 2);
                break;
            case R.id.difficultB:
                i.putExtra(GAME_LEVEL_KEY, 3);
                break;
        }
        startActivity(i);
    }

The putExtra() takes a string key, which we defined as

    static String GAME_LEVEL_KEY = "SelectedLevel";

so we can keep its name consistent everywhere.

Now, in the GameActivity onCreate() method, we can retrieve the parameter as follows:

        int level = getIntent().getIntExtra(MenuActivity.GAME_LEVEL_KEY, 1);

where the number 1 provides a default value in case no parameter matching GAME_LEVEL_KEY was passed in.