使用Cursor使,读取里面的数据用到getColumnIndex()时报错:
Index -1 requested, with a size of 1
仔细阅读过Cursor的文档,发现关于getColumnIndex()这个方法的说明如下:
public abstract int getColumnIndex (String columnName)
Since:
API Level 1
Returns the zero-based index for the given column name, or -1 if the column doesn't exist. If you expect the column to exist use getColumnIndexOrThrow(String)
instead, which will make the error more clear.
文档里清楚的表明:在要读取的列不存在的时候该方法会返回值“-1”。所以可知,以上报错可能是因为要get的列不存在,也可能是因为游标位置不对。后来发现,因为我在执行这个语句前没有执行“Cursor.moveToNext();”这个函数,导致游标还位于第一位置的前面,所以索引显示为“-1”,前面加上这句就没错了。
网上另有一种情况是用完Cursor没有关闭导致报此错误,所以也提醒各位用完Cursor要记得执行Cursor.close();