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:
creates an intent which, when executed with
startActivity, does two things:Game(specified by the parameterGame.class) andi(= the user input) into the activity, tagged with the string content ofKEY_DIFFICULTY.In the activity, this line:
reads the value that was set for
KEY_DIFFICULTYin the intent used to start the activity. Hence,diffnow contains the user-selected value (orDIFFICULTY_EASY, if the activity is started through a different intent which did not setKEY_DIFFICULTY).