Reputation: 1634
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
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:
moveToFirst()
, cursor is positioned at the first element with index 0.moveToNext()
. Movement succeeds, you are positioned at index 1.moveToNext()
. Movement succeeds, you are positioned at index 2, which is beyond the last element.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