【问题标题】:IndexOutOfBoundsException when using sqlite LIKE clause使用 sqlite LIKE 子句时出现 IndexOutOfBoundsException
【发布时间】:2017-12-05 06:27:23
【问题描述】:

我正在尝试从 sqlite 数据库中提取事件列表。 这是我使用的方法

public List<Event> printMonths(String eventId, String date) {
    List<Event> events = new ArrayList<>();
    String selectQuery = "SELECT eventName, date FROM events WHERE eventId = ? AND date LIKE ?";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, new String[]{eventId, "%" + date});
    if (cursor.moveToFirst()) {
        do {
                Event event = new Event();
                event.setName(cursor.getString(0));
                event.setDate(cursor.getString(1));
                events.add(event);
        } while (cursor.moveToNext());
    }
    db.close();
    return events;
}

返回错误 java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308)

如果我排除 LIKE 子句,一切正常。

为什么我会收到此错误以及如何解决此问题?

【问题讨论】:

  • 为什么你有like作为数组而不是字符串?
  • 使用while循环代替do while
  • 您的堆栈跟踪似乎与您的代码不匹配。例如,您没有在任何地方拨打get()
  • 我认为当你应用 LIKE 时你的光标返回 null
  • @CommonsWare 我简化了这个问题的原始代码。该代码确实可以在没有 LIKE 子句的情况下工作并返回所需的列表。我不明白为什么这个子句会用 IndexOutOfBoundsException 中断代码执行

标签: java android sqlite arraylist indexoutofboundsexception


【解决方案1】:

试试这个 -

public List<Event> printMonths(String eventId, String date) {
    List<Event> events = new ArrayList<>();
    String selectQuery = "SELECT eventName, date FROM events WHERE eventId = ? AND date LIKE ?";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, new String[]{eventId, "%" + date});
    if (cursor.moveToFirst()) {
    do {
            Event event = new Event();
            event.setName(cursor.getString(0));
            event.setDate(cursor.getString(1));
            events.add(event);
       } while (cursor.moveToNext());
   }
    db.close();
    return events;
}

【讨论】:

  • @sfirc 在 printMonths() 方法和 Adapter 类中检查您的数组列表大小
  • 天哪!你说得对!我忘记更改 Adapter 类中 getItemCount() 的返回值。非常感谢!
  • @sfirc 欢迎兄弟
  • 此代码将跳过第一行,请考虑使用 do-while。
【解决方案2】:

这对我很有用:

    String query= "SELECT " +columnName+ " FROM " + tableName+ " WHERE " + "eventId= " + eventiD+ " AND date LIKE = " + yourTargetDate

 try {

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {

       // Your code enter here 
       // example : event.setName(cursor.getString(cursor.getColumnIndex(Name)))

            cursor.moveToNext();

        }
    } finally {
        cursor.close();
        sqlDB.close();
    }

    return events;

【讨论】:

    猜你喜欢
    • 2019-05-28
    • 2016-04-02
    • 2014-07-28
    • 2023-03-11
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多