问题
I have an SQL query running on an 'sqlite' database that is throwing this exception: "java.lang.IllegalStateException: get field slot from row 0 col 0 failed" when I call:
db.rawQuery( "SELECT data FROM session_data WHERE session_id = ?", new String[] { String.format("%d", session_id) } );
if (!cursor.moveToFirst()) return;
bytes[] bytes = cursor.getBlob(0);
The column exists, and if I log in using adb shell sqlite3 /path/to/database.db I can successfully execute the same query.
The resulting cursor shows that there is 1 row selected with 1 column whose name is "data". The size of the blob is about 1.5 MB - could that be it? I have verified that cursor.GetColumnIndex("data") returns 0, so the column exists.
This is running on Android 2.1 SDK. Any ideas?
回答1:
The problem was that the blob was too big. It appears that cursor.getBlob(0) fails if the blob size is over a megabyte. Reading the blob in segments solved my issue:
// get length of blob data
Cursor cursor = db.rawQuery( "SELECT LENGTH(data) AS len FROM table WHERE id = ?", etc);
if (cursor == null || !cursor.moveToFirst()) throw new Exception("failed");
int size = cursor.getInt(cursor.getColumnIndexOrThrow("len"));
cursor.close();
// read a segment of the blob data
cursor = db.rawQuery( "SELECT SUBSTR(data,0,500000) AS partial FROM table WHERE id = ?", etc);
if (cursor == null || !cursor.moveToFirst()) throw new Exception("failed");
byte[] partial = cursor.getBlob(cursor.getColumnIndexOrThrow("partial"));
cursor.close();
// copy partial bytes, repeat until the whole length has been read...
回答2:
I assume that you are holding a reference to the cursor from the rawQuery.
Before you get any value from the cursor you need to call cursor.moveToFirst() because the cursor is initially positioned at -1. The correct way would be:
Cursor cursor = db.rawQuery( "SELECT data FROM session_data WHERE session_id = ?", new String[] { String.format("%d", session_id) } );
if(cursor!= null && cursor.moveToFirst()){ // checking if the cursor has any rows
bytes[] bytes = cursor.getBlob(0);
}
and also make sure that your column in the database is blob type
来源:https://stackoverflow.com/questions/6091949/what-could-be-the-cause-of-java-lang-illegalstateexception-get-field-slot-from