Android - 通过意图传递更多变量会导致应用程序崩溃

时间:2013-11-03 07:59:16

标签: java android debugging android-intent crash

因此,如果您点击播放随机活动(测验问题),则会显示主活动(主屏幕)中的代码。问题是,我试图将整数,默认分数传递给问题#1,其中分数将为5(这是默认值)。

 如果用户点击了错误的按钮,则会将用户导航到问题#2,对于问题#2,分数将为-2,小于2。

int defaultScore = 51;



// start Play Intent
public void onPlay(View view){
    Random r = new Random();
    int XML_random = r.nextInt(5)+1; // 5 different Quiz XML files
    Intent startQuiz = new Intent();
    switch(XML_random){
    case 1:
        startQuiz.setClass(view.getContext(), Quiz_1.class);
    break;
    case 2:
        startQuiz.setClass(view.getContext(), Quiz_2.class);
    break;
    case 3:
        startQuiz.setClass(view.getContext(), Quiz_3.class);
    break;
    case 4:
        startQuiz.setClass(view.getContext(), Quiz_4.class);
    break;
    case 5:
        startQuiz.setClass(view.getContext(), Quiz_5.class);
    break;
    } // end of the Random switch
    startQuiz.putExtra("passScore", defaultScore); 
    startActivity(startQuiz); 

}

所以,接下来如果选择随机活动,那么它的分数将是5,因为对于第一个问题,我希望用户以5开头作为开始。所以,这是一个激活(问题#1),如果用户点击了错误的按钮,那么问题#2就会显示出来。对于此活动,分数将为负2.因为用户选择了错误的答案。

问题1 - 用户点击了错误的按钮:

public class Quiz_1 extends Activity {
TextView textviewScore;
int current_score = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quiz_1);
    textviewScore = (TextView) findViewById(R.id.q_result);   // declaring the TextView 
    Bundle extras = getIntent().getExtras(); 
    if (extras != null) 
     {
       current_score   = extras.getInt("passScore");
    }

    textviewScore.setText(String.valueOf(current_score));

} // end of onCreate

public void on_quiz_1_wrong(View view){  // button clicked the wrong answer
    current_score = current_score - 2;
    Intent quiz1 = new Intent(this, Quiz_2.class);
    startActivity(quiz1);
    quiz1.putExtra("passNewScore", current_score);

}

这是问题#2,对于这项活动,我希望得分为负2。

public class Quiz_2 extends Activity {
TextView textviewScore;
int current_score = 0;
int getScore=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.quiz_2);
    textviewScore = (TextView) findViewById(R.id.q_result);   // declaring the TextView 
    Bundle extras = getIntent().getExtras(); 
    if (extras != null) 
     {
       current_score   = extras.getInt("passScore");
       getScore = extras.getInt("passNewScore");
    }
    current_score = current_score - getScore;
    textviewScore.setText(String.valueOf(current_score));

} // end of onCreate

2 个答案:

答案 0 :(得分:1)

你必须首先加注你的意图然后开始它。

 quiz1.putExtra("passNewScore", current_score);
 startActivity(quiz1);

答案 1 :(得分:0)

你没有在quiz1中传递密钥“passScore”的值并调用quiz2,那么你怎么能期望在quiz2中检索“passScore”的值?

在此方法on_quiz_1_wrong(View view)

中传递quiz1.java中键“passScore”的值