因此,如果您點擊播放隨機活動(測驗問題),將顯示主活動(主屏幕)中的代碼。問題是,我試圖將整數默認分數傳遞給問題#1,其中分數將是5(這是默認值)。
如果用戶點擊了錯誤的按鈕,它會引導用戶進入問題2,對於問題2,將比分minus2,小於2Android - 通過意圖傳遞更多的變體使應用程序崩潰
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
使用共享偏好用於此目的。 http://developer.android.com/guide/topics/data/data-storage.html#pref注意:這些數據將在用戶會話中持續存在(即使您的應用程序被終止)。所以下次您的活動開始並且您檢索得分時,您會得到持續存在的值。或使用數據庫 – Raghunandan
請發送logcat例外。 – Szymon
在你的代碼中是否隨機數是6或0呢? – Hardik