CursorIndexOutOfBoundsException:请求索引0,大小为0 - 数据库Android

时间:2015-06-04 12:37:42

标签: java android sqlite

我的程序中遇到了一些错误。 我正在尝试使用radiobutton制作测验应用程序。问答选项是从数据库中获得的。

这是我的代码的一部分:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* Get Intent Parameter */
    /* Open Database File */
    db_helper.openDataBase();
    db = db_helper.getReadableDatabase();


    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.setContentView(R.layout.activity_exercise_question);

    Qcontent = (TextView) findViewById(R.id.txtQuestion);
    Qnum = (TextView) findViewById(R.id.txtNumb);
    a = (RadioButton) findViewById(R.id.rbA);
    b = (RadioButton) findViewById(R.id.rbB);
    c = (RadioButton) findViewById(R.id.rbC);
    d = (RadioButton) findViewById(R.id.rbD);
    g = (RadioGroup) findViewById(R.id.rgOption);
    next = (Button) findViewById(R.id.btnNextQuestion);
    next.setBackgroundColor(Color.GREEN);

    //To handle event when button Next is clicked
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            int radioButtonID = g.getCheckedRadioButtonId();
            View radioButton = g.findViewById(radioButtonID);
            int idx = g.indexOfChild(radioButton);
            if (opsys.getString(idx + 1).equals(opsys.getString(5))) {
                nilai = nilai + 1;
            }
            quiz();
        }
    });
    quiz();
}


public void finish() {
    next.setText("Finish");
    next.setBackgroundColor(Color.RED);
    next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            int radioButtonID = g.getCheckedRadioButtonId();
            View radioButton = g.findViewById(radioButtonID);
            int idx = g.indexOfChild(radioButton);
            if (opsys.getString(idx + 1).equals(opsys.getString(5))) {
                score = score + 1;
            }
            ExerciseQuestion.this.finish();
            Intent showScore = new Intent(ExerciseQuestion.this, ExerciseScore.class);
            String achieveScore = String.valueOf(score);

            Bundle bundle = new Bundle();
            bundle.putString("AchieveScore", achieveScore);
            tampilNilai.putExtras(bundle);
            startActivity(showScore);
        }
    });
}

private void quiz() {
    question_numb = question_numb + 1;
    if (question_numb < 10) {
        Qnum.setText("  " + Integer.toString(question_numb) + '.');
    } else Qnum.setText(Integer.toString(question_numb) + '.');

    checkResult();

    Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
    a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
    b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
    c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
    d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton

    //To handle when question number is 10
    if (question_numb == 10) {
        finish();
    }
}

private boolean checkResult() {
    // TODO Auto-generated method stub
    int random10 = generateRandomNumber(10); //I've a method to generate Random number using Math.random() without repetition
    int random18 = generateRandomNumber(18);
    String query;

    Bundle bundle = getIntent().getExtras();
    int chooseContent = bundle.getInt("chooseContent");

    if (chooseContent == 0) {
        query = "SELECT question, a, b, c, d, answer FROM tbl_Exercise WHERE (id_topic=" + random18 + " and id_question=" + random10 + ")";
    } else {
        query = "SELECT question, a, b, c, d, answer FROM tbl_Exercise WHERE (id_topic=" + chooseContent + " and id_question=" + random10 + ")";
    }

    opsys = db.rawQuery(query, null);
    if (opsys != null && opsys.moveToFirst()) {
        return true;
    }
    opsys.close();
    return false;
}

有时当我触摸“下一步”按钮时,应用程序崩溃(但有时它不会崩溃,而且它的效果就像魅力一样)。 logcat如下:

06-04 19:14:16.884  10062-10062/com.coder.learningmodule E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coder.learningmodule, PID: 10062
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at com.coder.learningmodule.ExerciseQuestion.quiz(ExerciseQuestion.java:106)
        at com.coder.learningmodule.ExerciseQuestion.access$300(ExerciseQuestion.java:19)
        at com.coder.learningmodule.ExerciseQuestion$1.onClick(ExerciseQuestion.java:68)
        at android.view.View.performClick(View.java:4443)
        at android.view.View$PerformClick.run(View.java:18442)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5021)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
        at dalvik.system.NativeStart.main(Native Method)

错误是指Qcontent.setText(opsys.getString(0));方法

中的quiz()

在我阅读Stackoverflow中的一些相关问题后,我尝试了以下代码,但它没有解决问题

    opsys = db.rawQuery(query, null);
    if (opsys != null && opsys.moveToFirst()) {
        return true;
    }
    opsys.close();
    return false;           

我真的很感谢任何人的帮助和/或建议来解决这个问题。非常感谢你。

2 个答案:

答案 0 :(得分:1)

通过查看opsys nullmoveToFirst()的返回值,您走在了正确的道路上。如果这些检查成功,您的方法checkResult()会返回true,否则会返回false

您的问题是,在使用查询结果之前,您实际上没有检查此返回值:

checkResult();

Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton

相反,在访问值之前先检查返回的值

if(checkResult()) {
    Qcontent.setText(opsys.getString(0)); //this is to set the question I've taken from db to TextView
    a.setText(opsys.getString(1)); //this is to set the option A I've taken from db to radiobutton
    b.setText(opsys.getString(2)); //this is to set the option B I've taken from db to radiobutton
    c.setText(opsys.getString(3)); //this is to set the option C I've taken from db to radiobutton
    d.setText(opsys.getString(4)); //this is to set the option D I've taken from db to radiobutton
}

这样,如果实际存在任何返回值,则只访问查询结果。尝试访问没有行的结果会导致您的异常。

答案 1 :(得分:0)

您正在尝试从Cursor获取第一个结果,而不检查查询是否返回任何结果。你可以尝试这样的事情:

if(checkResult()){
    Qcontent.setText(opsys.getString(0));
    ...
    opsys.close();
}