2013-04-07 56 views
0

僅當列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"; 
     } 
+0

你已經做了大量的工作,通過你的遊標向後循環。我建議僅使用OrderBy參數/子句來爲您反轉結果,並使用'while(cursor.moveToNext())'或___調用'moveToLast()'和'while(cursor.moveToPrevious())'。那就是說,哪一行通過錯誤? – Sam 2013-04-07 19:27:38

回答

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循環。

希望這有助於...乾杯!

+0

解決了它。謝謝。 – 2013-04-07 19:45:13

+0

如果'j == -1',那麼'j> = 0'失敗,程序永遠不會進入循環。在第一次迭代之前評估終止表達式。 (顯然,我同意使用'moveToNext()',這很簡單。) – Sam 2013-04-07 22:23:28

相關問題