0

此错误仅在 COLUMN_NAME_DATE 列为空(该表中未创建条目)时发生。一旦我添加了一些条目,它就可以正常工作。我已经尝试了各种空检查,但没有任何效果。确切的错误:

android.database.CursorIndexOutOfBoundsException: Index -1 requested, 
 with a size of 0

这是错误的代码:

    if (cursor1.moveToFirst() == false) {
        Toast.makeText(this, "No categories found.", Toast.LENGTH_LONG).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));

            cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME,
                           null, 
                           TransactionsDbContract.TblTransactions.COLUMN_NAME_DATE + ">" + dateSent, 
                           null, null, null, null);

            for (int j = cursor2.getCount() - 1; j >= 0; j--) {
                cursor2.moveToPosition(j);
                catTotal += cursor2.getDouble(cursor2.getColumnIndexOrThrow(
                        TransactionsDbContract.TblTransactions.COLUMN_NAME_AMOUNT));
            }

            percent = catTotal/overallTotal * 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";
        }
4

1 回答 1

3

我猜你的错误在这里:

for (int j = cursor2.getCount() - 1; j >= 0; j--) {
    cursor2.moveToPosition(j); // j might be -1

...因为如果您的陈述...

cursor2 = db.query(TransactionsDbContract.TblTransactions.TABLE_NAME, ...);

... 不返回任何行,cursor2.getCount()为零,因此以 .j开头-1

我建议您使用...

while (cursor1.moveToNext()) {
    catTotal = 0;
    curCat = cursor1.getString(cursor1.getColumnIndexOrThrow(
                     CategoriesDbContract.TblCategories.COLUMN_NAME_CATEGORY));
    cursor2 = db.query(...);

    while (cursor2.moveToNext()) {
        catTotal += cursor2.getDouble(cursor2.getColumnIndexOrThrow(
                        TransactionsDbContract.TblTransactions.COLUMN_NAME_AMOUNT));
    }
}

...因为这样你就不需要for循环了。

希望这会有所帮助......干杯!

于 2013-04-07T19:33:27.460 回答