[英]Android - Passing more variebles via intent makes app 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
您必須首先多加注意,然后再開始。
quiz1.putExtra("passNewScore", current_score);
startActivity(quiz1);
您沒有在quiz1中傳遞鍵“ passScore”的值並調用quiz2,那么如何期望在quiz2中檢索“ passScore”的值?
通過此方法on_quiz_1_wrong(View view)
在quiz1.java中傳遞鍵“ passScore”的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.