此错误仅在 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";
}