使用sqlite LIKE子句

时间:2017-07-01 12:27:20

标签: java android sqlite arraylist indexoutofboundsexception

我正在尝试从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;
}

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子句,一切正常。

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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

这对我很有用:

    <activity android:name=".MyActivity"
              android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name">