【问题标题】:CursorIndexOutOfBoundsException during my query [SQLite]CursorIndexOutOfBoundsException 在我的查询 [SQLite]
【发布时间】:2016-11-12 17:45:18
【问题描述】:

我想在我的数据库中搜索KEY_TOR == place.getTor() 所在的行

这里我称之为方法:

DB_Place tor = db_tore.getDBPlace(place.getTor());

这是方法:

public DB_Place getDBPlace(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
                    KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
            new String[]{name}, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    DB_Place place = new DB_Place(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));

    return place;
}

对我来说看起来不错,除了我收到此错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.x.x/com.example.ahok.x.UI_MainActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

我在这里缺少什么?是否可能与null 的一些列有关?

【问题讨论】:

  • 尝试将这两行if (cursor != null) cursor.moveToFirst();合并为一行if (cursor != null && cursor.moveToFirst())
  • 顺便说一下,这是检索KEY_TOR的意义,如果你已经知道它的值是name
  • @Rotwang 做到了。还是一样的错误。
  • 另外,这个new String[]{name}, null, null, null, null);应该是new String[]{name});
  • @Rotwang 老实说,这对我来说是新的。我从另一个有效的查询中复制了这个。在这些查询中,我正在寻找 where 子句中的 id。您对如何更改方法有什么建议吗?

标签: java android sqlite android-sqlite


【解决方案1】:

您的数据库中似乎没有插入任何数据。此外,您的代码中有一些逻辑错误。

我想像这样编辑你的函数。

public DB_Place getDBPlace(String name) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_DB_TORE_Eintrag, new String[] { KEY_ID,
                    KEY_PLACE_ID, KEY_NAME, KEY_LONGITUDE, KEY_LATITUDE, KEY_TOR }, KEY_TOR + "=?",
                    new String[]{name}, null, null, null, null);

    DB_Place place = null;

    if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {

        place = new DB_Place(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
    }

    return place;
}

更新

因此,如果您认为这是您的查询错误,请像这样运行简单查询。

Cursor cursor = db.rawQuery("Select * from " + TABLE_DB_TORE_Eintrag + " where " + KEY_TOR + " = '" + name + "'", null);

【讨论】:

  • 我拿走了你的代码,至少应用程序不再崩溃了。该方法确实返回 place 为空,即使数据库不为空。我用返回整个数据库的方法检查了它。
  • 打印您在TABLE_DB_TORE_Eintrag 中的所有行并在此处发布。
  • 我认为 where 子句可能不起作用,但我不明白为什么。 name 是“Tor 1”,当我在数据库中检查时,存在一个条目,其中 KEY_TOR 是“Tor 1”
  • 请查看更新,如果有帮助请告诉我。
  • 我不确定如何打印它们,但这是获取该数据库中所有数据的方法的返回数组:Image of the Debugger
猜你喜欢
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 2021-03-18
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
  • 2018-02-17
  • 2017-09-24
相关资源
最近更新 更多