2013-02-26 32 views
0

當試圖運行我的應用程序時,我得到的錯誤,我無法弄清楚發生了什麼問題。我得到一個遊標超出限制的例外。Android應用程序的CursorIndexOutOfBoundsException

堆棧跟蹤:

02-26 12:33:56.870: D/AndroidRuntime(1012): Shutting down VM 
    02-26 12:33:56.870: W/dalvikvm(1012): threadid=1: thread exiting with uncaught exception (group=0x41452930) 
    02-26 12:33:56.870: E/AndroidRuntime(1012): FATAL EXCEPTION: main 
    02-26 12:33:56.870: E/AndroidRuntime(1012): java.lang.RuntimeException: Unable to create application com.example.myassistantcoach.AnotherHelper: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

這裏是我的代碼

private void readBowlingScoresFromDB() { 
     // TODO Auto-generated method stub 
     allBowlingScores = new ArrayList<BowlingScores>(); 
     Cursor bowlingScoresCursor; 
     bowlingScoresCursor = bowlingScoresDB.query(BOWLING_SCORES_TABLE, 
       new String[] { RECORD_ID, DATE, GAME1, GAME2, GAME3 }, null, 
       null, null, null, DATE); 
     bowlingScoresCursor.moveToFirst(); 
     BowlingScores tempBS; 
     if (!bowlingScoresCursor.isAfterLast()) { 
      do { 
       long id = bowlingScoresCursor.getLong(0); 
       long dateEpoch = bowlingScoresCursor.getLong(1); 
       int game1 = bowlingScoresCursor.getInt(2); 
       int game2 = bowlingScoresCursor.getInt(3); 
       int game3 = bowlingScoresCursor.getInt(4); 
       tempBS = new BowlingScores(id, dateEpoch, game1, game2, game3); 
       allBowlingScores.add(tempBS); 
      } while (bowlingScoresCursor.moveToNext()); 
      bowlingScoresCursor.close(); 
     } 
    } 

    public void addBowlingScores(BowlingScores bowlingScores) { 
     assert bowlingScores != null; 
     ContentValues cv = new ContentValues(); 
     cv.put(BowlingScoresDatabaseHelper.DATE, bowlingScores.getDateEpoch()); // USE 
                       // EPOCH 
     cv.put(BowlingScoresDatabaseHelper.GAME1, bowlingScores.getGame1()); 
     cv.put(BowlingScoresDatabaseHelper.GAME2, bowlingScores.getGame2()); 
     cv.put(BowlingScoresDatabaseHelper.GAME3, bowlingScores.getGame3()); 
     Log.d("Bowling Database", "Before Inserting a record" + bowlingScores); 
     long idPassedBack = bowlingScoresDB.insert(
       BowlingScoresDatabaseHelper.BOWLING_SCORES_TABLE, null, cv); 
     bowlingScores.setId(idPassedBack); 
     allBowlingScores.add(bowlingScores); 
    } 

回答

0

你的光標在你的第一次通過readBowlingScoresFromDB()空。我強烈建議使用for循環而不是使用if語句的do-while循環。這應該保持第一次迭代運行代碼並在光標爲空時跳過它。

for (bowlingScoresCursor.moveToFirst(); !bowlingScoresCursor.isAfterLast(); bowlingScoresCursor.moveToNext()) { 

      long id = bowlingScoresCursor.getLong(0); 
      long dateEpoch = bowlingScoresCursor.getLong(1); 
      int game1 = bowlingScoresCursor.getInt(2); 
      int game2 = bowlingScoresCursor.getInt(3); 
      int game3 = bowlingScoresCursor.getInt(4); 
      tempBS = new BowlingScores(id, dateEpoch, game1, game2, game3); 
      allBowlingScores.add(tempBS); 
} 

bowlingScoresCursor.close();