【问题标题】:CursorIndexOutOfBoundsException for table and records existing现有表和记录的 CursorIndexOutOfBoundsException
【发布时间】:2013-05-30 03:47:01
【问题描述】:

我正在使用以下查询查询数据库:

    final Cursor subject_cursor = db.rawQuery("SELECT * FROM " + DB.Table.SUBJECT + " WHERE uniqueSUB = '" + cs_cursor.getString(1) + "'", null);

当我记录游标计数时,它给我 1 作为计数,但是当我尝试使用 subject_cursor.getString(0) 访问数据时,它给我一个错误提示:

    05-30 03:37:10.921: W/System.err(5408): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

我已经手动检查了数据库中的记录,并且所有需要的数据都存在。 (另外,如果我只是执行以下查询:

    "SELECT * FROM " + DB.Table.SUBJECT"

对于同一个表并给出获取游标的计数,它给出了正确的现有记录数。

请帮忙...

【问题讨论】:

  • 那么您的查询可能没有正确执行。查询执行前cs_cursor.getString(1) 的值是多少?
  • @Shobhit Puri 它是 2
  • @ShobhitPuri 我已经检查并确认了!!!!

标签: java android sqlite sqliteopenhelper


【解决方案1】:

您绝对应该通读整篇帖子Cursor Index Out of Bounds Exception。它处理完全相同的问题,您可以在那里得到问题的答案。从帖子中获取并添加@Alexey 指出的内容,Cursorslazy loaded,您需要调用moveToFirst()moveToPosition() 等方法将它们加载到内存中。 moveToFirst 将光标移动到第一行,以便您可以访问它。同样,moveToPosition() 将光标移动到一个绝对位置。如果不使用这些函数,它会抛出你得到的错误。希望这可以帮助。

【讨论】:

  • 如果游标是延迟加载的,那么我如何获得列名:subject_cursor.getColumnName(0);
  • getColumnName 返回给定从零开始的列索引处的列名。它不取决于您作为查询结果获得的行。所以它会起作用。
  • 所以在我使用 where 子句查询然后使用 moveToFirst 或 moveToPosition 然后到达所需的记录后,我将不得不再次使用 where 子句查询表......不是它???
  • 没有。查询后,如果只想获取结果第一行的特定列值的值,则先将光标移动到第一行cursor.moveToFirst(),然后获取具有该索引的列中的值。即 cursor.getString(columnIndexValue)。这将为第一行提供columnIndexValue 列索引中的值。这取决于你想要什么。
  • 我想要我在 where 子句中描述的内容......所以很明显我想要记录特定于那个条件......所以如果我使用 subject_cursor.moveToFirst() 那么我没有得到我需要的记录!
【解决方案2】:
if(subject_cursor.moveToFirst()) 
    subject_cursor.getString(0);

【讨论】:

  • 好的....你只需要我解释一下光标延迟加载的事情...ShobhitPuri 帮了我...感谢您的回答
【解决方案3】:

把你的代码改成

 final Cursor subject_cursor = db.rawQuery("SELECT * FROM " + DB.Table.SUBJECT + " WHERE uniqueSUB = '" + cs_cursor.getString(0) + "'", null);

因为您的表中只有 1 行,并且您正尝试使用 cs_cursor.getString(1) 获取第二行

或者试试这个代码,

public void getAllEvents() {



    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_EVENTS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {




            // Adding contact to list
            MainActivity.Id.add(cursor.getString(0)); //it will store id to my array list "Id"


        } while (cursor.moveToNext());
    }


}

【讨论】:

  • 第二行是什么?? cs_cursor 用于另一个具有有效数据的表(我已经确认)...并且在第二个表的上述查询之后计数为 1....所以我找到了记录...只是我无法获取它使用 subject_cursor.getString(0)。
猜你喜欢
  • 2011-07-19
  • 1970-01-01
  • 2018-02-17
  • 2019-07-06
  • 1970-01-01
  • 2018-12-18
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多