简体   繁体   English

Android ArrayList索引超出范围

[英]Android ArrayList Index Out Of Bounds

I'm fairly new to Android and am having an issue with fetching data from my database. 我刚接触Android,从数据库中获取数据时遇到了问题。 I have an activity class which calls the database helper to get a list of questions according to a particular category. 我有一个活动类,该活动类调用数据库助手以根据特定类别获取问题列表。 The database should then put all of the questions into an ArrayList and return them. 然后,数据库应将所有问题放入ArrayList并返回它们。 The error seems to be occurring when I try and get the first question in the list of questions using: 当我尝试使用以下方法获取问题列表中的第一个问题时,似乎发生了错误:

Question question = questions.get(0);

Here is the relevant method in the activity class: 这是活动类中的相关方法:

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

    DatabaseHelper database = new DatabaseHelper(getApplicationContext());

    List<Question> questions = database.getQuestions(1);
    Question question = questions.get(0);

    TextView questionText = (TextView) findViewById(R.id.QuestionText);
    questionText.setText(question.getText());
}

Database Helper: 数据库助手:

// Get All The Question From Database For A Specific Category And Put Them Into A List Of Question
public List<Question> getQuestions(int category) {
    List<Question> questions = new ArrayList<Question>();

    String selectQuery = "SELECT * FROM " + TABLE_QUESTION +
            " WHERE " + KEY_CATEGORY_ID + " = '" + category + "'";

    Log.e(LOG, selectQuery);

    database = this.getReadableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        // Loops Through The Database To Get All Question Matching Category
        do {
            Question question = new Question();

            question.setId(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ID)));
            question.setNumber(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_NUMBER)));
            question.setText(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_TEXT)));
            question.setMarks(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_MARKS)));
            question.setAnswer(cursor.getInt(cursor.getColumnIndex(KEY_QUESTION_ANSWER)));
            question.setMC1(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC1)));
            question.setMC2(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC2)));
            question.setMC3(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC3)));
            question.setMC4(cursor.getString(cursor.getColumnIndex(KEY_QUESTION_MC4)));

            // Add The Question To The List Of Question
            questions.add(question);
        } while (cursor.moveToNext());
    }
    return questions;
}

Finally, here is the logcat: 最后,这是logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.revision.aschemistry/com.revision.aschemistry.AtomicStructureQuestions}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
        at android.app.ActivityThread.access$600(ActivityThread.java:123)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
        at java.util.ArrayList.get(ArrayList.java:304)
        at com.revision.aschemistry.AtomicStructureQuestions.onCreate(AtomicStructureQuestions.java:26)
        at android.app.Activity.performCreate(Activity.java:4465)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
            at android.app.ActivityThread.access$600(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
            at dalvik.system.NativeStart.main(Native Method)

Any help is much appreciated, thanks in advance. 感谢您的任何帮助,在此先感谢。

It seems your ArrayList Question is Empty. 看来您的ArrayList问题为空。 So just check size before getting data from it. 因此,仅在获取数据之前检查大小即可。

List<Question> questions = database.getQuestions(1);
if(!questions.isEmpty())
{
 Question question = questions.get(0);
}else
{
 Log.e("LOG","questions  is Empty")
}

Also check Cursor size in your getQuestions() method from DatabaseHelper class. 还要从DatabaseHelper类的getQuestions()方法中检查Cursor大小

Obviously you can use: 显然,您可以使用:

if(!questions.isEmpty())

To avoid the the ArrayIndexOutOfBounds Exception. 避免ArrayIndexOutOfBounds异常。 But I guess that dosen't Solve our problem dose it? 但是我想这不能解决我们的问题吗?

I hope our solution here is to read the data properly and then retrieve the data using the get() method of Arraylist. 我希望这里的解决方案是正确读取数据,然后使用Arraylist的get()方法检索数据。

There needs to be a check before reading the data. 在读取数据之前,需要进行检查。 Please check if the data are feed properly first and then go for getting them. 请先检查数据是否正确输入,然后再获取它们。 I would like to suggest some posts you can follow to get idea about Databases. 我想建议一些帖子,您可以按照这些帖子了解数据库。

  1. http://www.vogella.com/tutorials/AndroidSQLite/article.html http://www.vogella.com/tutorials/AndroidSQLite/article.html
  2. http://infobloggall.com/2014/05/06/sqlite-database-example http://infobloggall.com/2014/05/06/sqlite-database-example

Also the developer site. 也是开发者网站。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM