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?
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:
Game
(specified by the parameter Game.class
) andi
(= 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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With