YaphetHayate 2022-02-16 20:30 采纳率: 100%
浏览 186
已结题

安卓cursor.moveToNext()遍历sqlite数据库次数错误

问题遇到的现象和发生背景

在学习并尝试从sqlite读取数据并展示在listview中,我的sqlite数据库中只有39行数据,然而用while (cursor.moveToNext());却会一直循环702次。

问题相关代码
    Cursor cursor = db.rawQuery("select * from foodTable",null);
    Integer xhcs =0 ;
    while (cursor.moveToNext()); {
        list.add(new FoodList(cursor.getString(cursor.getColumnIndex("foodname"))
                , cursor.getString(cursor.getColumnIndex("exclude"))
                , cursor.getString(cursor.getColumnIndex("resid"))));
        xhcs=xhcs+1; //记录循环次数}
    cursor.close();
    db.close();

    for (int i = 0; i < list.size(); i++) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("foodname", list.get(i).foodname);
        map.put("exclude", list.get(i).exclude);
        map.put("resid", list.get(i).resid);
        listitem.add(map);
    }
    Log.d(TAG,xhcs.toString());
运行结果及报错内容

运行后在正确的生成一轮item之后会继续从第一个item开始再重复多轮。

我的解答思路和尝试过的方法

在数据库里用select * from foodTable语句能正常返回39条结果,用select count(*) from foodTable也返回39
尝试过用cursor.moveTofirst定位或是用while(!cursor.isAfterLast()),依然会循环702次。

我想要达到的结果

正确循环39次后停止,想知道为啥会这样。。702/39=18次,也就是说多循环了18次。。就算算上列我的数据库也才39*6=234个格子。。

  • 写回答

2条回答 默认 最新

  • 关注

    用for循环试试:

    if(cursor.moveToFirst()){
    for(int i=0;i<cursor.getCount();i++{
    
    
    cursor.move(i);
    list.add(new FoodList(cursor.getString(cursor.getColumnIndex("foodname"))
                    , cursor.getString(cursor.getColumnIndex("exclude"))
                    , cursor.getString(cursor.getColumnIndex("resid"))));
            xhcs=xhcs+1; //记录循环次数}
    
    。。。
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月17日
  • 已采纳回答 2月17日
  • 创建了问题 2月16日

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装