Tofira
Tofira

Reputation: 1634

Cursor out of bounds exception when inserting values to Database - Android

I'm trying to insert values from a cursor to my database, but I get an error.

Here's what I do -

    Cursor getUserDrinks = myDbHelper.getUserDrinks();
    if(getUserDrinks != null)
    {
        if (getUserDrinks.moveToFirst()){
               do{
                    ContentValues initialValues = new ContentValues();
                    initialValues.put("code", getUserDrinks.getInt(getUserDrinks.getColumnIndex("code")));
                    initialValues.put("imgstr", getUserDrinks.getString(getUserDrinks.getColumnIndex("imgstr")));
                    initialValues.put("name", getUserDrinks.getString(getUserDrinks.getColumnIndex("name")));
                    initialValues.put("alc", getUserDrinks.getDouble(getUserDrinks.getColumnIndex("alc")));
                    initialValues.put("user", 1);

                    try {  
                           myDataBase.beginTransaction();
                           myDataBase.insert("drinks", null, initialValues);
                           myDataBase.setTransactionSuccessful();
                           } 
                       finally {
                           myDataBase.endTransaction();
                           }
               }while(getUserDrinks.moveToNext());
        }
    }

But it gives me a CursorIndexOutOfBoundsException. Here's the Log -

04-30 13:22:35.363: ERROR/AndroidRuntime(19161): java.lang.RuntimeException: Unable to         start activity ComponentInfo{android.alco/android.alco.main}: android.database.CursorIndexOutOfBoundsException: Index 2 requested, with a size of 2

I know that the Cursor is not empty.

What am I doing wrong?

Upvotes: 0

Views: 718

Answers (1)

Malcolm
Malcolm

Reputation: 41510

The problem is that moveToNext() returns false when you are already positioned after the last element and want go further. Range of valid positions is from -1 to elementCount inclusive, so the last position is legitimate, but there's no element. This is what really happens in your code if the cursor has two positions:

  1. You call moveToFirst(), cursor is positioned at the first element with index 0.
  2. You read the values and call moveToNext(). Movement succeeds, you are positioned at index 1.
  3. You read the values and call moveToNext(). Movement succeeds, you are positioned at index 2, which is beyond the last element.
  4. You try to read the values and fail because there is no element with index 2.

What you need to do is the following:

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
    //Read the contents
    cursor.moveToNext(); //Advance to the next element
}

Upvotes: 1

Related Questions