Error using cursor to read Sqlite table

Asked

Viewed 665 times

0

I’m having the following mistake:

Couldn’t read Row 0, col -1 from Cursorwindow. Make sure the Cursor is initialized correctly before accessing data from it.

however to my view the cursor was initialized correctly in the first position as you can see:

SQLiteDatabase db = openOrCreateDatabase("meudb",MODE_PRIVATE,null);


db.execSQL("CREATE TABLE IF NOT EXISTS pessoas(nome VARCHAR, IDADE INT(3))");
    db.execSQL("INSERT INTO PESSOAS(nome,idade) VALUES('davi', 25)");
    db.execSQL("INSERT INTO PESSOAS(nome,idade) VALUES('marcos', 31)");
    db.execSQL("INSERT INTO PESSOAS(nome,idade) VALUES('thiago', 50)");
    db.execSQL("INSERT INTO PESSOAS(nome,idade) VALUES('bruna', 24)");
    db.execSQL("INSERT INTO PESSOAS(nome,idade) VALUES('vanessa', 18)");




    Cursor cursor = db.rawQuery("SELECT nome,idade FROM pessoas",null);
    int colunaNome = cursor.getColumnIndex("nome");
    int colunaIdade = cursor.getColumnIndex("idade");

    cursor.moveToFirst();
    while (cursor != null){
        Log.i("Nome: ",cursor.getString(colunaNome));
        Log.i("Idade: ",cursor.getString(colunaIdade));
        cursor.moveToNext();
    }
 }}

1 answer

1


Cursor is being accessed before cursor.moveToFirst(). Besides that while condition always returns true.

Do so:

Cursor cursor = db.rawQuery("SELECT nome,idade FROM pessoas",null);

if(cursor != null && cursor.moveToFirst()){
    do{
        Log.i("Nome: ", cursor.getString(cursor.getColumnIndex("nome")));
        Log.i("Idade: ", cursor.getString(cursor.getColumnIndex("idade")));
    }while(cursor.moveToNext());
}
  • I did as you said but the error still persists... I do not understand why even checking with a condition it still accuses that the cursor is not initialized in the correct way

  • You have all that code in one method?

  • Yes, everything running on Mainacivity

  • Then that must be the problem. Look for Sqliteopenhelper to know how to implement the bank.

  • I created another project and copied and pasted the code and it worked... I think android studio bugged, but thank you very much

Browser other questions tagged

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