Reputation: 223
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?
Upvotes: 4
Views: 65293
Reputation: 694
Intents are used to start an activity programmatically in android. The intent can carry data, which you pass to the new started activity.
startGame(int i)
starts the new game activity with an intent. Putting an extra to an intent means, you are passing data over to the intent. The started activity (in your case the Game.java) then can acceess this extra from the intent.
It is a mechanism to pass data between activities.
The first argument (KEY_DIFFICULTY) is the key by which the extra is identified. So if you put an extra to an intent with key 'mykeyexample' you will have to do a get with the same key 'mykeyexample' in another activity to get the desired extra from the intent.
Hope this helps
Upvotes: 1
Reputation: 172280
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
).
Upvotes: 14