Java 如何从一个活动到另一个活动获取变量,然后使用该变量
我正在开发一个应用程序,它将在文本视图中显示分数,然后在另一个活动中获得该分数。我使用以下代码执行此操作:Java 如何从一个活动到另一个活动获取变量,然后使用该变量,java,android,Java,Android,我正在开发一个应用程序,它将在文本视图中显示分数,然后在另一个活动中获得该分数。我使用以下代码执行此操作: //in the first activity int score= 0; score= score + 5; txtscore.setText("Score: " + score); Intent intent = new Intent(context, AnotherActivity.class);
//in the first activity
int score= 0;
score= score + 5;
txtscore.setText("Score: " + score);
Intent intent = new Intent(context, AnotherActivity.class);
intent.putExtra("Score",score+ " ");
context.startActivity(intent);
//in second activity (AnotherActivity.class)
Bundle bundle = getIntent().getExtras();
if (bundle != null){
int score= bundle.getInt("0");
txtscore.setText("0" + score);
}
现在我需要在第二个类中使用静态方法保存在txtscore中的分数,其中需要添加5分,总计10分
我有一个静态方法:
private static void rotate{
//some tasks being done
if (isSolved()){
int new =0;
// need to get value from another activity here and save to x
new = x + 10;
txtscore.setText("Score: " + new );
}
}
有什么帮助吗?只需使用:
getIntent().getExtras().getString("Score");
在第二个活动中与其将分数作为字符串传递(随后必须将其解析为int),不如将分数捆绑为int: 活动一 活动二
int score = 5;
Intent.putExtra("score", score);
int score = bundle.getIntExtra("score");
score += 5;
txtScore.setText("SCORE: " + score);