Android光标索引超出界限

时间:2014-07-04 11:52:11

标签: android null cursor indexoutofboundsexception

在我的应用程序中,我有许多SQL查询,它们将表中的行数据传输到文件中。在这些问题中,我有我的Sql游标,基本上按照另一个的值对我的列进行排序,然后拉出第一行的值。问题是,一旦光标到达我的表的末尾,那么应用程序因为零值而崩溃。

    public static String evalLightTable(String filenamePrefix){


    String[] lightcolumns = new String[] { KEY_ROWID, KEY_TID, KEY_NAME, KEY_LUXVALUE, KEY_TRANSMITTED};
    Cursor elightcursor = myDatabase.query(LIGHT_TABLE, lightcolumns, KEY_TID + "=" + filenamePrefix + " AND " + KEY_TRANSMITTED + "=" + nottransmitted, null, null, null, null);       
    String notTransmitted = "";

    int iRowId = elightcursor.getColumnIndex(KEY_ROWID);

    if (elightcursor != null) {
        elightcursor.moveToFirst();
        String lightRowId = elightcursor.getString(0);
        return lightRowId;
    }
    return null;
}

以上是我正在运行的示例查询。以下是适用的logCat:

07-04 13:21:14.697: E/AndroidRuntime(19537): android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

07-04 13:21:14.697: E/AndroidRuntime(19537):    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)

在我的查询中,我要求它只要光标找到某些内容就可以检索数据。应该是,如果没有,它肯定不会崩溃。

2 个答案:

答案 0 :(得分:0)

游标不包含任何结果行。在访问数据之前,您应该检查moveTo..()是否成功。

此外,query()中的SQLiteDatabase永远不会返回null,因此空检查是多余的。

因此,请替换

if (elightcursor != null) {
    elightcursor.moveToFirst();

if (elightcursor.moveToFirst()) {

答案 1 :(得分:0)

试试这个,你没有检查结果计数。以及删除变量iRowId。

    public static String evalLightTable(String filenamePrefix){


String[] lightcolumns = new String[] { KEY_ROWID, KEY_TID, KEY_NAME, KEY_LUXVALUE, KEY_TRANSMITTED};
Cursor elightcursor = myDatabase.query(LIGHT_TABLE, lightcolumns, KEY_TID + "=" + filenamePrefix + " AND " + KEY_TRANSMITTED + "=" + nottransmitted, null, null, null, null);       
String notTransmitted = "";


if (elightcursor != null && elightcursor.getCount() > 0 ) {
    elightcursor.moveToFirst();
    String lightRowId = elightcursor.getString(0);
    return lightRowId;
}
return null;

}

相关问题