Cursor的moveToFirst和moveToNext

SQLiteDatabase db;
Cursor c = db.query("pic", null, null, null, null,null, null);
Toast.makeText(AndroidStudyActivity.this,"当前共有" + c.getCount() + "条记录,下面一一显示:",Toast.LENGTH_SHORT).show();
//循环显示
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
Toast.makeText(AndroidStudyActivity.this,"第"+ c.getInt(0)  +"条数据,文件名是" + c.getString(1) + ",描述是"+c.getString(2), Toast.LENGTH_SHORT).show();

}
查询得到的cursor是指向第一条记录之前的,这个看一下SQLiteDatabase类的query方法的返回值说明就明白了,即:

     * @return A {@link Cursor} object,which is positioned before the first entry
     * @see Cursor
     */
    public Cursor query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy) {
        return query(false, table, columns, selection, selectionArgs, groupBy,
                having, orderBy, null /* limit */);
    }

,因此查询得到cursor后第一次调用moveToFirst(实际要向后移一个位置)或moveToNext(从指向第一条记录之前向后移动一个位置变为刚好指向第一条记录位置)都可以将cursor移动到第一条记录上。

源码中这些moveXXX其实都是通过moveToPosition来实现的,而记录position的是一个整型变量mPos。当moveXXXX返回false的时候,mPos会被置为-1,也就是回到了初始状态,指向第一条记录之前。


posted on 2011-11-29 21:04  封起De日子  阅读(302)  评论(0编辑  收藏  举报

导航