Reputation:
I wish to pass the value of score from one activity to another. I addExtras to the intent and getExtras in the new activity but it doesn't seem to get the value.
Activity 1;
Intent intent = new Intent(Game.this, EndGame.class);
intent.putExtra("put_score", score);
startActivity(intent);
Game.this.finish();
Activity 2;
Bundle extras = getIntent().getExtras();
if (extras != null) {
score = extras.getString("put_score");
}
setContentView(R.layout.endgame);
scoreResult = (TextView) findViewById(R.id.scoreNum);
scoreResult.setText(score);
Upvotes: 0
Views: 110
Reputation: 11234
You problem is coming from the following piece of code in Bundle.java:
try {
return (String) o;
} catch (ClassCastException e) {
typeWarning(key, o, "String", e);
return null;
}
Here o
is the object you put to the bundle (bundle actually has a core storage of type Map<String, Object>
, so, due to autoboxing, when you put int
to the bundle, it will become Integer
). But, unfortunately, Integer
cannot be casted to String
explicitly, so you get null
instead. In other words: if you put int
, then use getInt
to retrieve the value.
Upvotes: 2
Reputation: 6082
you placed data in intent using putExtra
not putExtras
so read them the same way
use getXXExtra() XX is the dataType your data is,
based on the example, if score is Integer, then use:
getIntExtra("put_score", 0);//0 zero is default in case data was not found
http://developer.android.com/reference/android/content/Intent.html
Upvotes: 1