引起:android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1

时间:2013-05-05 04:17:10

标签: android sqlite cursor

我想从我的数据库中选择值,但我收到了错误

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

我不知道我的代码在哪里出错了.. 这是我在dbHelper中的代码。

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

我希望在其他课程中获得价值。 我使用这段代码。

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

我正在搜索,但我没有得到我的错误的解决方案。 有人能帮助我吗? 我真的需要解决方案,请帮帮我.. 谢谢.. 此致..

3 个答案:

答案 0 :(得分:4)

您需要将光标移动到第一个,“k_id”应该是“idkontak”。

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

答案 1 :(得分:1)

光标官员docs说:

功能:getColumnIndex(String columnName):

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

因此,如果您在错误中获得Index -1 requested,则表示该列不存在。因此,请尝试将列添加为@StinePike建议,或者您可以尝试获取所有行:

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

然后使用正确的列名:

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

希望有所帮助。

答案 2 :(得分:0)

使用

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