java - 从游标返回错误值

标签 java android sqlite cursor

在我看来,这完全是超自然现象。我得到了这个将数据库数据转换为对象的小函数:

public List<BudgetSummary> getMonnthlyBalance() {
    List<BudgetSummary> list = new ArrayList<BudgetSummary>();

    DbAdapter db = new DbAdapter(context);
    SQLiteDatabase sqldb = db.open();
    MonthlyBalanceSqlSelect sql = new MonthlyBalanceSqlSelect();
    Cursor cursor = sql.getCursor(sqldb);

    while (cursor.moveToNext()) {
        list.add(new BudgetSummary(cursor));
    }

    cursor.close();
    db.close();
    return list;
}

MonthlyBalanceSqlSelect 包含 sql 查询,我将其从调试器复制到 Sqliteman。我已经从应用程序中提取了数据库文件。结果如下:

enter image description here

这对我来说看起来很完美。现在让我们看一下 BudgetSummary 构造函数。就像电线一样简单。

public BudgetSummary(Cursor cursor) {
    incomes = cursor.getDouble(cursor.getColumnIndex("incomes"));
    expenses = cursor.getDouble(cursor.getColumnIndex("expenses"));     
}

我正在对这个构造函数内的每次迭代进行单步调试。它应该与图片上显示的数据相对应,但事实并非如此......结果如下:

 1. incomes: 4732.0 - wrong   | expenses: -57.59 - wrong     | month and year correct
 2. incomes: 4657.0 - correct | expenses: -3714.96 - correct | month and year correct
 3. incomes: 708.0 - wrong    | expenses: -3383.03 - correct | month and year correct
 4. incomes: 5669.48 - wrong  | expenses: -5669.48 - wrong   | month and year correct
 5. incomes: 3278.5 - correct | expenses: -2685.91 - wrong   | month and year correct
 6. incomes: 4612.5 - wrong   | expenses: -2786.78 - wrong   | month and year correct
 and so on...

这是什么魔法?我真的不知道...为什么有些值是正确的,而其他值却完全出乎意料?

这是 SQL 查询。我强烈怀疑java看待它的方式与Sqliteman根据this不同。 。不幸的是我不知道它应该是什么样子。

select strftime('%m', b.date) as month , strftime('%Y', b.date) as year, total(case when b.value >= 0 then b.value else 0 end) as incomes, total(case when b.value < 0 then b.value else 0 end) as expenses from budget b, category c where b.category_id = c.id group by month, year order by year desc, month desc

最佳答案

强烈怀疑问题在于您假设 Sqliteman 和 Java 代码中的行排序相同。除非您的 SQL 显式指定顺序,否则您不应假设它是相同的。我建议您在查询中包含月份和年份,并将其包含在 BudgetSummary 中,至少用于诊断。

关于java - 从游标返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15797703/

相关文章:

java - 更新 AsyncTask 内的 ArrayAdapter 的有效方法?

android - Admob 横幅广告未在 Android 中加载

android - 将 Dagger2 与数据库一起使用

android - 使用 greendao 3 从 2 个不同实体获取值

linux - 是否有用于在 Linux 中验证 SQLite 数据库的命令行实用程序?

Android:如何取消/中断/中断挂起的 SQLite 查询?

java - 确定此 REST 应用程序背后的工具?

java - child 有不同 parent 的树结构

java - 如何在 gradle 中的类路径之外指定 quartz 属性文件?

Android:屏幕旋转会改变视频大小