What could be the cause of “java.lang.IllegalStateException: get field slot from row 0 col 0 failed”

老子叫甜甜 提交于 2020-01-03 04:53:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!