Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getIntExtra() and putExtra()?

I read Hello Android book and i dont understan the following code. I dont know, what to do getIntExtra() and putExtra() int this code.

 private void startGame(int i) {
     Log.d(TAG, "clicked on " + i);
     Intent intent = new Intent(Sudoku.this, Game.class);
     intent.putExtra(Game.KEY_DIFFICULTY, i);
     startActivity(intent);
 }

Game.java

public class Game extends Activity {
    private static final String TAG = "Sudoku" ;
    public static final String KEY_DIFFICULTY ="org.example.sudoku.difficulty" ;
    public static final int DIFFICULTY_EASY = 0;
    public static final int DIFFICULTY_MEDIUM = 1;
    public static final int DIFFICULTY_HARD = 2;
    private int puzzle[] = new int[9 * 9];
    private PuzzleView puzzleView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate" );
        int diff = getIntent().getIntExtra(KEY_DIFFICULTY,DIFFICULTY_EASY);
        puzzle = getPuzzle(diff);
        calculateUsedTiles();
        puzzleView = new PuzzleView(this);
        setContentView(puzzleView);
        puzzleView.requestFocus();
    }
    // ...
}

The problem I have is that you are setting a local integer (‘diff’) within the Game class. with a default value of zero (easy) and then immediately passing it into the getPuzzle method …. how does the user input value ( the real value all being well) ever find it’s way into the getPuzzle method?

like image 218
Pariya Avatar asked Dec 07 '22 12:12

Pariya


1 Answers

This code:

 Intent intent = new Intent(Sudoku.this, Game.class); 
 intent.putExtra(Game.KEY_DIFFICULTY, i); 
 startActivity(intent); 

creates an intent which, when executed with startActivity, does two things:

  • It starts a new activity of class Game (specified by the parameter Game.class) and
  • it passes i (= the user input) into the activity, tagged with the string content of KEY_DIFFICULTY.

In the activity, this line:

 int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY); 

reads the value that was set for KEY_DIFFICULTY in the intent used to start the activity. Hence, diff now contains the user-selected value (or DIFFICULTY_EASY, if the activity is started through a different intent which did not set KEY_DIFFICULTY).

like image 148
Heinzi Avatar answered Dec 22 '22 15:12

Heinzi