2014-05-08 117 views
0

我希望将分数值从一个活动传递给另一个活动。我在新活动中添加了意图和getExtras,但似乎没有获得该值。在Android中的活动之间传递数据?

活动1;

Intent intent = new Intent(Game.this, EndGame.class); 
     intent.putExtra("put_score", score); 
     startActivity(intent); 
     Game.this.finish(); 

活动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); 
+1

有什么问题? – MatheusJardimB

+0

您在'scoreResult'处看到什么值? – nikis

+0

活动1中得分值为19,活动2得分值为零。它似乎没有提供或得到分数值。 – Seatter

回答

1

您放置在使用putExtraputExtras 所以看过他们以同样的方式

使用 意图数据getXXExtra() XX是你的数据是具体的数据类型的基础上,例如

,如果得分为整数,则使用:

getIntExtra("put_score", 0);//0 zero is default in case data was not found 

http://developer.android.com/reference/android/content/Intent.html

2

您的问题是从下面这段代码进来Bundle.java

try { 
    return (String) o; 
} catch (ClassCastException e) { 
    typeWarning(key, o, "String", e); 
    return null; 
} 

这里o是你投入到捆绑的对象(包实际上有Map<String, Object>类型的核心存储,因此,由于自动装箱,当你把int添加到捆绑包时,它将变成Integer)。但是,不幸的是,Integer不能被明确地铸造到String,所以你得到null。换句话说:如果你把int,然后使用getInt检索值。

+0

你回答得太好....干杯 – EdmDroid

+0

但是...他根本没有添加任何包!他用putExtra(String,Int)不是putExtras(Bundle)!! – Yazan

+1

@Yazan这只是简写的方法。所有额外的数据存储在包 – nikis

相关问题