简体   繁体   中英

Android ArrayList Index Out Of Bounds

I'm fairly new to Android and am having an issue with fetching data from my database. 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. 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:

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. 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.

Obviously you can use:

if(!questions.isEmpty())

To avoid the the ArrayIndexOutOfBounds Exception. 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.

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
  2. http://infobloggall.com/2014/05/06/sqlite-database-example

Also the developer site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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