开发者

How can I transfer my score from one activity to another on Android?

This is how I used my integer from one activity. It开发者_StackOverflow社区's a matching type question and the corresponding radio button is one of the answers. The correct radiobutton would give the score of 1.

Integer score1;
public void onCheckedChanged(RadioGroup group, int rb1) {
  switch(rb1){
  case R.id.radioButton1:
     score1=0;
     break;
  case R.id.radioButton2:
     score1=0;
     break;
  case R.id.radioButton3:
     score1=0;
     break;  
  case R.id.radioButton4:
     score1= 1;
     break;  
}

On the result screen I will be usng the integer like this:

totalscore = score1 +score2 .....

How do I transfer score1 from the activity with the radio buttons to the activity for the result screen?


Try

Integer score1, totalscore;

public void onCheckedChange(RadioGroup group, int rb1) {
    switch (rb1) {
        case R.id.radioButton1:
            score1=0;
            break;
        case R.id.radioButton2:
            score1=0;
            break;
        case R.id.radioButton3:
            score1=0;
            break;  
        case R.id.radioButton4:
            score1= 1;
            totalscore += 1;
            break;  
     }
}


First off, you can greatly simplify your switch logic:

Integer score1;
public void onCheckedChanged(RadioGroup group, int rb1) {
    score1 = (rb1 == R.id.radioButton4) ? 1 : 0;
}

Second, there are several different ways to pass score1 from one Activity to another. For instance, when you create your Intent for the second Activity, you can use putExtra() to store your score value, and then the second Activity can use getExtra() to read the value when it starts.

Or you can use any of a number of quick but questionable hacks, such as making score1 a public static field, or passing it around via system properties, or writing it out to an agreed-upon file location, or storing it to an agreed-upon field in a database (these hacks only work if there is only a single instance of your activity per device, and are really not recommended at all).

Really though you should just stick with getExtra() and putExtra(). Along the lines of:

//in QuestionActivity
private Integer score1;

//...

public void onCheckedChanged(RadioGroup group, int rb1) {
    score1 = (rb1 == R.id.radioButton4) ? 1 : 0;
    Intent resultIntent = new Intent(this, ResultActivity.class);
    resultIntent.putExtra("score1", score1);
    startActivity(resultIntent);
}


//in ResultActivity
private Integer score1;

//...

@Override
protected void onStart() {
    score1 = this.getIntent().getExtras().getInt("score1");
    super.onStart();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜