我取当前日期,然后将月份的日期设置为1.然后,在查询中,我说已经存储在数据库中的日期必须在此日期之后或之后发生。您将从代码中看到,比较的日期以毫秒为单位。
我的问题是当我在数据库中创建一个条目,并设置该月的第一天的日期时,由于某种原因它永远不会包含在结果中。但是,如果我只是将其设置为当前月份的第2个,它将按预期工作。我希望错误是围绕此查询的某个地方。至少如果这一切对你来说都很好,我会知道我的逻辑在其他地方一定是错的。
编辑:有问题的查询是第二次设置为cursor2的查询(在第一个for循环中)。
public void buildTable () {
SQLiteDatabase db = BalanceDb.getInstance(this).getDB();
String curCat = "", category = "", spent = "";
double catTotal, percent, curBudget;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 1);
long backDate = cal.getTimeInMillis();
Cursor cursor1 = db.query(CategoriesDbContract.TblCategories.TABLE_NAME,
null, null, null, null, null, null);
Cursor cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME,
null, null, null, null, null, null);
if (cursor1.moveToFirst() == false) {
Toast.makeText(this, "No categories found.", Toast.LENGTH_SHORT).show();
}
else {
for (int i = cursor1.getCount() - 1; i >=0; i--) {
catTotal = 0;
cursor1.moveToPosition(i);
curCat = cursor1.getString(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY));
curBudget = cursor1.getDouble(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_BUDGET));
cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME,
null,
TransactionsDbContract.TblTransactions.COLUMN_NAME_CATEGORY + "= '" + curCat + "'" +
"AND " + TransactionsDbContract.TblTransactions.COLUMN_NAME_DATE + ">=" + backDate,
null, null, null, null);
for (int j = cursor2.getCount() - 1; j >= 0; j--) {
cursor2.moveToPosition(j);
catTotal += -1 * (cursor2.getDouble(cursor2.getColumnIndexOrThrow(
TransactionsDbContract.TblTransactions.COLUMN_NAME_AMOUNT)));
}
percent = catTotal/curBudget * 100;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(1);
String percStr = df.format(percent);
category += cursor1.getString(cursor1.getColumnIndexOrThrow(
CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY)) + "\n";
spent += percStr + "\n";
}
textCat.setText(category);
textSpent.setText(spent);
}
}
答案 0 :(得分:2)
根据The Rationalist解决方案编辑回答。
小时将是您拨打cal.set(Calendar.DATE, 1);
时需要更改的时间
cal.set(Calendar.DATE, 0);