Error returning Android Cursor

Asked

Viewed 351 times

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 making a mistake on 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

2 answers

2


When using a cursor you should first test if it is not null and then test if you have records at the same time you move it to the first.

On the other hand, the resulting cursor of

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

has only one record with a column of the 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) 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 your request as int:

int id_pedido;
  • 1

    I understood. It is really this value that is returning from the query is an int that would be the ID. Thank you very much for the collaboration.

0

Failed to move cursor to first item, as you did with cursor2.

cursor1.moveToFirst()
  • I just noted that. Thank you very much.

  • Celso would actually be: cursor1.moveToLast(); Because I need the last id, I already send the cursor to the last line. Anyway, thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.