僅當列COLUMN_NAME_DATE爲空(該表中沒有條目)時纔會出現此錯誤。一旦我添加了一些條目,它工作正常。我已經嘗試了各種空檢,什麼都沒有,但沒有任何工作。完全錯誤:當WHERE子句中的列爲空時,我的SQLite查詢會導致cursorindexoutofbounds異常。我該如何阻止?
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";
}
你已經做了大量的工作,通過你的遊標向後循環。我建議僅使用OrderBy參數/子句來爲您反轉結果,並使用'while(cursor.moveToNext())'或___調用'moveToLast()'和'while(cursor.moveToPrevious())'。那就是說,哪一行通過錯誤? – Sam 2013-04-07 19:27:38