从游标返回的值错误

时间:2013-04-03 20:42:06

标签: 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

1 个答案:

答案 0 :(得分:1)

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