您的位置:首页 > 产品设计 > UI/UE

【我的问题】关于cursor查询的用法的注意事项(Index -1 requested, with a size of 1)

2014-08-28 10:39 369 查看
使用Cursor使,读取里面的数据用到getColumnIndex()时报错:
Index -1 requested, with a size of 1

/**

* query(...)对执行数据表执行行查询,注意:已经确定行号了

*/

Cursor cursor=getContentResolver().query(nowPlayingUri, null, null, null, null);

/**

* 为什么一定要cursor.moveToNext()或cursor.moveToFirst()这个方法才是正确的?

* 答:因为query()方法已经确定了行,因此cursor游标只有一行的范围可以游动

* 因此,当执行完query()语句后,cursor游标已经到了末尾了,因为只有一句,所以末尾是空值。

* 这时游标指向的是没有值的行,所以会报错。

*/

if (cursor.getCount() != 0)

{

cursor.moveToFirst();

Log.d("mLog","cursor.getCount()="+cursor.getCount());

}

另外还可以参考下面的内容(转载)http://blog.csdn.net/hehuanluoluo/article/details/6231097

使用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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐