0

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);
5
  • what value to you see at the scoreResult? Commented May 8, 2014 at 14:10
  • The value of score in activity 1 is 19, the value of score in activity 2 is null. It doesn't seem to either put or get the score value. Commented May 8, 2014 at 14:10
  • Depending on your manifest settings you might have to capture the intent in onNewIntent(), try overriding that method and see if it receives the expected result. Commented May 8, 2014 at 14:10
  • 7
    What type is score? If it is not a String, when you call extras.getString() it will be null. Use extras.getInt() if it is an int. Commented May 8, 2014 at 14:10
  • Thanks, Little brain fart there ha, Why I was getting a String is beyond me. Thanks for pointing that out :) Commented May 8, 2014 at 14:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but ... he did not add a bundle at all! he used putExtra (String,Int) not putExtras(Bundle)!!
@Yazan it's just shorthand method. All extra data is stored in bundle
@nikis, did not know that before! dirty secrets of android :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.