使用Cursor时出现了 Index 3 requested, with a size of 3 的报错,当时使用的写法如下:
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
c.move(i);
list.add(c.getString(2));
}
}
其实文档里面有说明:
/**
* Move the cursor by a relative amount, forward or backward, from the
* current position. Positive offsets move forwards, negative offsets move
* backwards. If the final position is outside of the bounds of the result
* set then the resultant position will be pinned to -1 or count() depending
* on whether the value is off the front or end of the set, respectively.
*
* <p>This method will return true if the requested destination was
* reachable, otherwise, it returns false. For example, if the cursor is at
* currently on the second entry in the result set and move(-5) is called,
* the position will be pinned at -1, and false will be returned.
*
* @param offset the offset to be applied from the current position.
* @return whether the requested move fully succeeded.
*/
boolean move(int offset);
move(i)这个方法并不是移动到第i行,而是基于当前位置移动i行,如果只是遍历结果集,建议使用下面的语句:
while(c.moveToNext()){
list.add(c.getString(2));
}
本文解析了在使用Cursor进行数据操作时常见的Index3requested错误,并详细解释了Cursor移动方法的工作原理。文章通过对比move(i)与moveToNext()的用法,指导开发者如何正确遍历结果集,避免因误解move方法而导致的程序错误。
145

被折叠的 条评论
为什么被折叠?



