java.lang.IndexOutOfBoundsException:索引3无效,大小为3

时间:2014-11-30 05:57:57

标签: java android eclipse

如何修复IndexOutOfBoundsException的错误? 我正在创建一个测验类型的应用程序,但只要我完成回答问题并继续执行ResultActivity,它的力就会关闭。 请帮我。谢谢!

public class QuizActivity extends Activity {
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    DBHelper db=new DBHelper(this);
    quesList=db.getAllQuestions();
    currentQ=quesList.get(qid);
    txtQuestion=(TextView)findViewById(R.id.textView1);
    rda=(RadioButton)findViewById(R.id.radio0);
    rdb=(RadioButton)findViewById(R.id.radio1);
    rdc=(RadioButton)findViewById(R.id.radio2);
    butNext=(Button)findViewById(R.id.button1);
    setQuestionView();
    butNext.setOnClickListener(new View.OnClickListener() {     
        @Override
        public void onClick(View v) {
            RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
            RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
            Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
            if(currentQ.getANSWER().equals(answer.getText()))
            {
                score++;
                Log.d("score", "Your score"+score);
            }
            if(qid<5){                  
                currentQ=quesList.get(qid);
                setQuestionView();
            }else{
                Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
                Bundle b = new Bundle();
                b.putInt("score", score); //Your score
                intent.putExtras(b); //Put your score to your next Intent
                startActivity(intent);
                finish();
            }
        }
    });
}

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

1 个答案:

答案 0 :(得分:0)

你不应该对问题的数量进行硬编码,特别是因为你看起来像是一个问题。使用List的长度来检查越界。

改变 -

 if(qid<5){                  
     currentQ=quesList.get(qid);
     setQuestionView();
 }

 if(qid < quesList.size()){                  
     currentQ=quesList.get(qid);
     setQuestionView();
 }