Reputation: 11
I'm making a score list for a game, I had used the following code to pass the scoretime to ScoreActivity, but I don't know why it will only show the default number "1"
long timeSpent = System.currentTimeMillis() - initialTime;
timeSpent = (long) (timeSpent / 1000.0);
int apple = (int)timeSpent;
Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);
AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this).create();
alertDialog.setTitle("Game Over!");
alertDialog.setMessage(" Total time " + String.valueOf(timeSpent));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i =new Intent(getContext(), ScoreActivity.class);
getContext().startActivity(i);
}
In ScoreActivity
TextView myText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
myText = (TextView)findViewById(R.id.text444);
Intent scoreIntent = getIntent();
int rating = scoreIntent.getIntExtra("score", 1);
String str = Integer.toString(rating);
myText.setText(rating);
}
Upvotes: 1
Views: 48
Reputation: 2202
It shows the default value because you created an intent and put extras in it
Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);
that's right but when you started the activity you used another intent
Intent i =new Intent(getContext(), ScoreActivity.class);
getContext().startActivity(i);
and the value of apple
isn't in the new intent i
so a solution is to make your intent scoreIntent
as final
which you can access from your onClick()
method like:
final Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);
and from onClick()
you do this
getContext().startActivity(scoreIntent );
Upvotes: 2
Reputation: 3243
You need pass your value here
Intent i =new Intent(getContext(), ScoreActivity.class);
i.putExtra("score",Apple);
getContext().startActivity(i);
Upvotes: 0