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 に答える