Reputation: 473
Whenever I click on the button, it should change the score if the answer is correct. However, when i click on next, it does not change the score. it just shows its default which is 0. Everything is okay except for the score.
public class QuizActivity extends Activity {
DBAdapter db = new DBAdapter(this);
private TextView tvQuestion;
private Cursor c;
private Cursor cur;
private RadioGroup radioGroup;
private RadioButton rb0,rb1,rb2;
private Button nextButton;
private int i =1;
private int questNo=0;
private RadioButton radioButton;
private int score=0;
private String correctAnswer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quizactivity);
displayQuestion();
nextButton = (Button) findViewById(R.id.nextButton);
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
getselectedAnswer();
checkAnswer();
if(i < 10){
i=i+1;
radioGroup.clearCheck();
displayQuestion();
}else{
Intent i = new Intent(QuizActivity.this, Results.class);
startActivity(i);
}
}
});
}
public void checkAnswer() {
Cursor mCursor = db.getCorrectAnswersforComparison(i);
String correctAns = mCursor.getString(mCursor.getColumnIndex(DBAdapter.KEY_CORRECTANSWERS));
if(getselectedAnswer()==correctAns){
score = score+1;
}else{
score = score+0;
}
}
private String getselectedAnswer() {
if (rb1.isChecked()){
return rb1.getText().toString();
}
if (rb2.isChecked()){
return rb2.getText().toString();
}
if (rb0.isChecked()){
return rb0.getText().toString();
}
else
return null;
}
public void displayQuestion(){
db.open();
TextView scoretv = (TextView) findViewById(R.id.scoretv);
scoretv.setText(""+score);
c = db.getQuiz_Content(i);
cur = db.getAnswers(i);
tvQuestion = (TextView) findViewById(R.id.textViewQuestionQA);
tvQuestion.setText(c.getString(0));
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
String correctAnswer = cur.getString(cur.getColumnIndex(DBAdapter.KEY_CORRECTANSWERS));
String option1 = cur.getString(cur.getColumnIndex(DBAdapter.KEY_OPTION1));
String option2 = cur.getString(cur.getColumnIndex(DBAdapter.KEY_OPTION2));
rb0 = (RadioButton) findViewById(R.id.radio0);
rb1 = (RadioButton) findViewById(R.id.radio1);
rb2 = (RadioButton) findViewById(R.id.radio2);
List<String> answers = new ArrayList<String>();
answers.add(correctAnswer);
answers.add(option1);
answers.add(option2);
Collections.shuffle(answers);
rb0.setText(answers.get(0));
rb1.setText(answers.get(1));
rb2.setText(answers.get(2));
}
}
Upvotes: 0
Views: 2193
Reputation: 1910
Your problem is here:
if(getselectedAnswer()==correctAns)
String comparison on Java doesn't work with the usual equality operator == (this checks if they are the same instance, not whether the strings contain the same characters). Instead, use the string method .equals:
if(getSelectedAnswer().equals(correctAns))
Upvotes: 2