Android SQLite中Cursor易错合集
第一次上手几乎把SQLite能犯的错都示范了个遍==。
现在马一下,免得以后忘了又焦头烂额。
错误1:android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
原因:使用cursor对象前未将指针移至开头
解决办法:在使用corsor.getString()等方法前加上cursor.moveToFirst();
错误2:java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
原因:使用cursor.getString()中寻找了不存在的column,即返回的cursor结果中只有在db.query();指定查询的列名里(第二个参数)所写明的信息项被保留了。
解决办法:①去除访问了保留信息项以外的语句
②将要访问的信息项加入到第二参数中
③将第二参数更改为null
错误3:java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
原因:db.query();的筛选条件(第三参数)里格式不正确,比如要表达“NAME==第一行代码”,写成了“NAME”
解决办法:将“NAME”改为“NAME=?” (其中“第一行代码”放在第四参数中)
错误4: android.database.sqlite.SQLiteException: no such column: ASC (code 1): , while compiling: SELECT name, AUTHOR FROM BOOK WHERE NAME=? ORDER BY ASC
原因:排序规则漏写了,只写“ASC”是无法升序排列的,应该指明按照什么来升序排列
解决办法:加入排序对象,如“NAME ASC”,就是按NAME排序