androidDev
androidDev

Reputation: 141

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

i want to select value from my database but i got error

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

i don't know where is the wrong in my code.. this is my code in dbHelper.

public Cursor pilihKontak( String nomor ) {
    Cursor c = dba.rawQuery("SELECT idkontak FROM TB_kontak where nomor = '"+nomor+"'", null);
    return c;
}

and i want to get the value in other class. i use this code.

Cursor cursorKontak = data.pilihKontak(nomor);
    idkontak = cursorKontak.getString(cursorKontak.getColumnIndex("k_id"));

i've searching and i didn't get the solution of my error. can somebody help me? i really need the solution, please help me.. thanks.. Regards..

Upvotes: 2

Views: 2538

Answers (3)

Hoan Nguyen
Hoan Nguyen

Reputation: 18151

You need to move the cursor to first and "k_id" should be "idkontak".

Cursor cursorKontak = data.pilihKontak(nomor);
if (cursorKontak.moveToFirst()) {
    idkontak = cursorKontak.getString(cursorKontak.getColumnIndex("idkontak"));
}

Upvotes: 4

Shobhit Puri
Shobhit Puri

Reputation: 26007

The Cursor official docs say:

Function: getColumnIndex(String columnName):

It returns the zero-based index for the given column name, or -1 if the column doesn't exist.

So if you are getting Index -1 requested in the error, it means the column does not exist. So try to include the column as @StinePike suggested, or you may try to get all the rows:

 Cursor c = dba.rawQuery("SELECT * FROM TB_kontak where nomor = '"+nomor+"'", null);

Then use the correct column name:

 Cursor cursorKontak = data.pilihKontak(nomor);
 idkontak = cursorKontak.getString(cursorKontak.getColumnIndex("CORRECT_COLUMN_NAME"));

Hope that helps.

Upvotes: 1

stinepike
stinepike

Reputation: 54682

use

Cursor c = dba.rawQuery("SELECT k_id FROM TB_kontak where nomor = '"+nomor+"'", null);

Upvotes: 0

Related Questions