I wrote extension functions for reading from cursor:
fun SQLiteDatabase.query(table: String,
columns: Array<String>,
selection: String? = null,
selectionArgs: Array<String>? = null): Cursor =
query(table, columns, selection, selectionArgs, null, null, null)
fun Cursor.readRows(onRowRead: (Cursor) -> Unit) {
if(moveToFirst()) {
do {
onRowRead(this)
} while (moveToNext())
}
}
fun Cursor.getString(field: String): String = getString(getColumnIndex(field))
fun Cursor.getInt(field: String) = getInt(getColumnIndex(field))
And it mostly works perfect. But recently happened strange error in the followng SQLiteOpenHelper
function:
fun loadPresentationStatistic(stringParser: (String) -> PresentationStatistic): ArrayList<PresentationStatisticInformation> {
val db = readableDatabase
val c = db.query(TABLE_PRESENTATION_STATISTIC, arrayOf(ROW_ID, ROW_PRESENTATION_STATISTIC))
val result = arrayListOf<PresentationStatisticInformation>()
c.readRows {
result.add(PresentationStatisticInformation(it.getInt(ROW_ID),stringParser(it.getString(ROW_PRESENTATION_STATISTIC))))
}
c.close()
return result
}
Error stacktrace:
java.lang.IllegalStateException: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it. android.database.CursorWindow.nativeGetLong(Native Method) android.database.CursorWindow.getLong(CursorWindow.java:511) android.database.CursorWindow.getInt(CursorWindow.java:578) android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:84) com.example.DBWorkerKt.getInt(DBWorker.kt:480) com.example.DBHelper$loadPresentationStatistic$1.invoke(DBWorker.kt:342)
If I get it right, that means moveToFirst
returns true for empty cursor, so getInt
function throws this exception. How could that be?
The worst thing is that I can't reproduce it. It happens only on one particular device - all other users works as they should.