2016-10-19 4 views
0

Я программирую свое первое приложение для Android.

Я пытаюсь создать приложение для викторины. У меня есть вопросы, хранящиеся в базе данных SQLite, которые отображаются один за другим.
Пользователь выбирает один из ответов (переключатель) и нажимает кнопку «Следующая кнопка», и отображается следующий вопрос и так далее.

Следующий код показывает мой файл дел, отображающий каждый вопрос один за другим, что было отлично работает.

Показать следующую запись в базе данных


ACEActivity (старая, рабочая версия)

public class ACEActivity extends Activity { 
List<Question> quesList; 
int score = 0; 
int qid = 0; 
Question currentQ; 
TextView txtQuestion; 
RadioButton rda, rdb, rdc, rdd; 
Button butNext; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_quiz); 

    DatabaseHelper db = new DatabaseHelper(this); 

    quesList = db.getAllACEQuestions(); 
    currentQ = quesList.get(qid); 
    txtQuestion = (TextView)findViewById(R.id.textView); 
    rda = (RadioButton)findViewById(R.id.radio0); 
    rdb = (RadioButton)findViewById(R.id.radio1); 
    rdc = (RadioButton)findViewById(R.id.radio2); 
    rdd = (RadioButton)findViewById(R.id.radio3); 
    butNext = (Button)findViewById(R.id.nextButton); 
    setQuestionView(); 

    butNext.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      RadioGroup grp = (RadioGroup)findViewById(R.id.radioGroup); 
      RadioButton answer = (RadioButton)findViewById(grp.getCheckedRadioButtonId()); 
      Log.d("yourans", currentQ.getANSWER() + " " + answer.getText()); 
      // If the correct answer was clicked display the next question 
      if(currentQ.getANSWER().equals(answer.getText())) { 
       currentQ = quesList.get(qid); 
       setQuestionView(); 
      } 
     } 
    }); 
} 

// Load the next question 
private void setQuestionView() { 
    txtQuestion.setText(currentQ.getQUESTION()); 
    rda.setText(currentQ.getOPTA()); 
    rdb.setText(currentQ.getOPTB()); 
    rdc.setText(currentQ.getOPTC()); 
    rdd.setText(currentQ.getOPTD()); 
    qid++; 
    } 
} 


В моей новой версии этой деятельности я загружаю другую деятельность, чтобы дать немедленный пользователь обратной связи, если правильный или неправильный ответ был нажат.

После отображения обратной связи я хотел бы вернуться к этой операции и отобразить следующий вопрос.

Я пытаюсь сделать это, передав идентификатор вопроса из активности обратной связи (ACECorrectActivity) в эту деятельность (ACEActivity) без каких-либо успехов.



Как я пытался решить эту проблему:

ACEActivity (новая версия, только работая на первый вопрос)

public class ACEActivity extends Activity { 
List<Question> quesList; 
int score = 0; 
int qid = 0; 
Question currentQ; 
TextView txtQuestion; 
RadioButton rda, rdb, rdc, rdd; 
Button checkBtn; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_quiz); 

    // THIS PART IS NEW ================================ 
    // Get the intent 
    Intent intent = getIntent(); 
    // Get the question id (if there are any extras) 
    Bundle extras = intent.getExtras(); 
    if (extras != null) { 
     int qid = extras.getInt("nextQuestionID"); 
    } else { 
     int qid = 0; 
    } 
    // ================================================== 

    DatabaseHelper db = new DatabaseHelper(this); 

    quesList = db.getAllACEQuestions(); 
    currentQ = quesList.get(qid); 
    txtQuestion = (TextView)findViewById(R.id.textView); 
    rda = (RadioButton)findViewById(R.id.radio0); 
    rdb = (RadioButton)findViewById(R.id.radio1); 
    rdc = (RadioButton)findViewById(R.id.radio2); 
    rdd = (RadioButton)findViewById(R.id.radio3); 
    checkBtn = (Button) findViewById(R.id.checkButton); 

    setQuestionView(qid); 

    checkBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup); 
      RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId()); 
      Log.d("yourans", currentQ.getANSWER() + " " + answer.getText()); 
      // THIS PART IS NEW AND WORKING FINE ================================ 
      // If the correct answer was clicked 
      if (currentQ.getANSWER().equals(answer.getText())) { 
       Intent intent = new Intent(ACEActivity.this, CorrectACEActivity.class); 
       startActivity(intent); 
      // If the wrong answer was clicked 
      } else { 
       Intent intent = new Intent(ACEActivity.this, FalseACEActivity.class); 
       startActivity(intent); 
      } 
     } 
    }); 
} 

private void setQuestionView() { 
    txtQuestion.setText(currentQ.getQUESTION()); 
    rda.setText(currentQ.getOPTA()); 
    rdb.setText(currentQ.getOPTB()); 
    rdc.setText(currentQ.getOPTC()); 
    rdd.setText(currentQ.getOPTD()); 
    qid++; 
    } 
} 

ACECorrectActivity (активность обратной загруженную, когда правильный ответ выбирается, а следующая кнопка нажата в ACEActivity)

public class CorrectACEActivity extends Activity { 
List<Question> quesList; 
int score = 0; 
int qid = 0; 
Question currentQ; 
TextView txtQuestion; 
RadioButton rda, rdb, rdc, rdd; 
Button nextBtn; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_correct); 

    DatabaseHelper db = new DatabaseHelper(this); 

    quesList = db.getAllACEQuestions(); 
    currentQ = quesList.get(qid); 
    txtQuestion = (TextView) findViewById(R.id.textView); 
    rda = (RadioButton) findViewById(R.id.radio0); 
    rdb = (RadioButton) findViewById(R.id.radio1); 
    rdc = (RadioButton) findViewById(R.id.radio2); 
    rdd = (RadioButton) findViewById(R.id.radio3); 
    nextBtn = (Button) findViewById(R.id.nextButton); 

    // Set colors according to correct answer 
    rda.setBackgroundColor(Color.RED); 
    rdb.setBackgroundColor(Color.RED); 
    rdc.setBackgroundColor(Color.RED); 
    rdd.setBackgroundColor(Color.RED); 

    if(currentQ.getANSWER().equals(currentQ.getOPTA())) { 
     rda.setBackgroundColor(Color.GREEN); 
    } else if(currentQ.getANSWER().equals(currentQ.getOPTB())) { 
     rdb.setBackgroundColor(Color.GREEN); 
    } else if(currentQ.getANSWER().equals(currentQ.getOPTC())) { 
     rdc.setBackgroundColor(Color.GREEN); 
    } else if(currentQ.getANSWER().equals(currentQ.getOPTD())) { 
     rdd.setBackgroundColor(Color.GREEN); 
    } 

    setQuestionView(); 

    // WHEN NEXT BUTTON IS CLICKED RETURN TO ACEActivity AND LOAD NEXT QUESTION 
    nextBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(CorrectACEActivity.this, ACEActivity.class); 
      intent.putExtra("nextQuestionID", currentQ + 1); 
      startActivity(intent); 
     } 
    }); 
} 

private void setQuestionView() { 
    txtQuestion.setText(currentQ.getQUESTION()); 
    rda.setText(currentQ.getOPTA()); 
    rdb.setText(currentQ.getOPTB()); 
    rdc.setText(currentQ.getOPTC()); 
    rdd.setText(currentQ.getOPTD()); 
    qid++; 
    } 
} 


Первый вопрос работает отлично. Однако, как только я вернусь к ACEActivity после ответа на первый вопрос, мне снова будет задан первый вопрос.


Как вы можете видеть, я действительно новичок в этом и был бы очень рад за любую помощь! Спасибо!!

ответ

1
intent.putExtra("nextQuestionID", currentQ + 1); 

Вы устанавливаете лишнее неправильное значение в CorrectACEActivity, не так ли?

intent.putExtra("nextQuestionID", qid+ 1); 
+0

Спасибо за ваш ответ! Ты прав. С моим кодом также много других проблем. Поэтому я попытаюсь полностью изменить макет моего проекта. Но большое спасибо за указание на это! – Schwesi

+0

Я рад, что помог. , пожалуйста, отметьте это как ответ – Farid

Смежные вопросы