【问题标题】:Can't extract table from a Select query Cursor in SQLite (Android)无法从 SQLite(Android)中的选择查询游标中提取表
【发布时间】:2012-07-23 23:22:38
【问题描述】:

我有一个表,我必须从中获取 KEY_DATE = dat 的行。

然后我将这些行保存为对象并返回这些对象的列表。

问题是,如果我的表中有 4 个条目,那么我将获取最后一行 4 次,而不是获取所有 4 行。

这是我的代码...

while(!l.isEmpty())
    {
        hd = l.get(0);
        l.remove(0);
        map = new HashMap<String, String>();
        Log.w("myapp",hd._name+hd._price+hd._qty);

        map.put("item", hd._name);
        map.put("price", Double.toString(hd._price));
        map.put("qty", Integer.toString(hd._qty));
        map.put("total", Double.toString(hd._price*hd._qty));
        mylist.add(n++,map);
    }

    SimpleAdapter mSchedule = new SimpleAdapter(getActivity(), mylist, R.layout.details_item_list, new String[] {"item", "price", "qty" , "total"}, new int[] {R.id.col1, R.id.col2, R.id.col3, R.id.col4});
    list.setAdapter(mSchedule);

项目正在被检索,但我的列表视图显示的最后一项仅与我的 sql 表中的项目数相乘。我是否在循环中正确使用了 map.put() 和 add() 函数。

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    那是因为您只有一个 HistoryDetails 实例,您在 List 中添加了 4 次,并在每次迭代时对其进行修改。您需要将 hd = new HistoryDetails(); 放入循环中,例如

    hd = new HistoryDetails();
    
    hd._qty = Integer.parseInt(cursor.getString(3));
    hd._name = c.getString(1);
    hd._price = Double.parseDouble(c.getString(2));
    
    l.add(hd);
    

    【讨论】:

    • 尝试记录 id 以确保每次迭代都不同:Log.d("getMyHistoryOnDate", "id is: " + id);
    • 是的,它起作用了,但现在问题出在我的列表视图中显示这些项目。检查我的新编辑
    • 知道了,忘了在循环中包含新的哈希图。
    【解决方案2】:
        .....
        Cursor cursor = .......   
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
    
            hd = new HistoryDetails();  // IMPORTANT !!!!
    
            hd._qty = Integer.parseInt(cursor.getString(3));
            hd._name = cursor.getString(1);
            hd._price = Double.parseDouble(cursor.getString(2));
    
            l.add(hd);
    
            cursor.moveToNext();
        }
        cursor.close();
        .......
    

    【讨论】:

    • 你使用光标 c; (未定义!!!!!)和光标光标(已定义!!!)在您的代码中。删除光标 c;
    • Cursor cdo {} while () 循环内定义
    • 游标 c 定义在 do while 循环中,使用它从另一个表中提取数据。
    • 我正在使用您的代码在 logcat 中释放 GC_Concurrent,这意味着存在一些内存泄漏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多