Problems with showing data from Cursor in Android
I get the following error in my LogCat when running my application:
06-28 13:39:57.827: ERROR/AndroidRuntime(10490): java.lang.RuntimeException: Unable to start activity ComponentInfo{random.test/random.test.ResultsActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 2
The code that triggers the error:
myCursor.getString(0)
I've checked out my SQL query, it works fine when i run it in SQLite Database Browser (I've pulled the db from my emulator, no alterations). It returns 1 column, with 2 rows:
--------
| test |
--------
| asd1 |
--------
| asd2 |
--------
When I run getColumnIndex("test") on my 开发者_开发问答cursor it returns '0'. So I'm all out of ideas here, it says an existing column doesn't exist?
You probably need to call moveToFirst() on the Cursor before you try to use it. Also, getColumnIndex(String) returns a 0 based index, so if it returns 0, then it is a valid column. -1 would suggest that the column doesn't exist.
You should do myCursor.moveToFirst() before trying to access data.
The getColumnIndex("test") just let you know the index for the column. It says nothing regarding the number of rows... You can have 0 rows from a table with 'n' columns.
So getColumnIndex("test") with a result of 0 just says you have a column in the position 0.
Regarding the myCursor.getString(0), the error is because you don't have any results. Did you move the cursor to the first element? Don't forget to call moveToFirst()...
Hope this helps you...
精彩评论