Android Cursor return error

1
public boolean insertData( int id_item, String nome, int quantidade) {
    String preco_unitario = "0";
    String id_pedido = "0";
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    String sql1  = "SELECT MAX(id) AS id FROM "+ TABLE_PEDIDO ;
    Cursor cursor1 = db.rawQuery(sql1, null);
    if(cursor1.getCount() > 0) {
        id_pedido =    cursor1.getString(cursor1.getColumnIndex(COL_0_PEDIDO));
    }
    contentValues.put(COL_1_ITEM_PEDIDO, id_pedido);
    contentValues.put(COL_2_ITEM_PEDIDO, id_item);
    contentValues.put(COL_3_ITEM_PEDIDO, nome);
    contentValues.put(COL_4_ITEM_PEDIDO, quantidade);
    String sql2 = "SELECT preco FROM " + TABLE_PRECO + " WHERE id_item = " + id_item;
    Cursor cursor2 = db.rawQuery(sql2,null);
    cursor2.moveToFirst();
    if(cursor2.getCount() > 0){
        preco_unitario = cursor2.getString(cursor2.getColumnIndexOrThrow(COL_3_PRECOS));
    }
    double total = quantidade * Double.parseDouble(preco_unitario);
    contentValues.put(COL_5_ITEM_PEDIDO, preco_unitario);
    contentValues.put(COL_6_ITEM_PEDIDO, total);
    long result = db.insert(TABLE_ITEM_PEDIDO, null, contentValues);
    if (result == -1) {
        return false;
    } else {
        return true;
    }

You're giving an error in this part:

if(cursor1.getCount() > 0) {
    id_pedido =    cursor1.getString(cursor1.getColumnIndex(COL_0_PEDIDO));
}

Error message:

  

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

    
asked by anonymous 12.08.2016 / 16:58

2 answers

2

When using a cursor, you must first test if it is not null and then test if it has records at the same time that you move it to the first one.

On the other hand, the resulting cursor from

String sql1  = "SELECT MAX(id) AS id FROM "+ TABLE_PEDIDO ;
Cursor cursor1 = db.rawQuery(sql1, null);

has only one record with a column of type int . The best way to get the value of this column is to use cursor1.getInt(0);

Note that the error is due to cursor1.getColumnIndex(COL_0_PEDIDO) to be returning -1 .

Change this part of the code to:

if (cursor != null){
    if(cursor.moveToFirst())//Move para o primeiro

        id_pedido = cursor1.getInt(0));

    }
}

Declare requested_id as int :

int id_pedido;
    
12.08.2016 / 17:26
0

You have failed to move the cursor to the first item, as you did with the cursor2.

cursor1.moveToFirst()
    
12.08.2016 / 17:15