2012-03-24 122 views
3

即時通訊學習如何使用sqlite數據庫,我試圖在我製作的遊戲中實現高分系統。閱讀行的作品,當我嘗試顯示分數,但當我嘗試使用相同的想法來讀取值來比較它們在下面的方法 - 它給出一個空指針異常錯誤。奇怪的nullPointerException錯誤 - 數據庫相關

private void checkIfHighScore(int currentScore) { 
    Cursor note; 
    int rowScore; 
    String moveName, moveScore, newName; 

    for (long i=1;i<6;i++){ 
     note = mDbHelper.fetchNote(i); 
     startManagingCursor(note); 
     rowScore=Integer.parseInt(note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_BODY))); 
     if (currentScore<rowScore){ 
      for (long j=5;j>i;j--){ 
       note = mDbHelper.fetchNote(j-1); 
       startManagingCursor(note); 
       moveName=note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_TITLE)); 
       moveScore=note.getString(note.getColumnIndexOrThrow(ScoresDbAdapter.KEY_BODY)); 
       mDbHelper.updateNote(j, moveName, moveScore); 
      } 
      newName="a"; //for testing 
      mDbHelper.updateNote(i, newName, Integer.toString(currentScore)); 
      break; 
     } 
    } 

} 

我知道錯誤是在for循環之後 - 但我不知道是什麼導致它失敗。我的數據庫有5行數據(已驗證)。 有誰知道是什麼原因導致我的錯誤?一直在我的頭上撞牆2小時。謝謝!

+6

'mDbHelper'如何聲明和初始化? – 2012-03-24 09:21:50

+1

它可能是:'mDbHelper'未初始化,或'mDbHelper.fetchNote(i)'返回null(我們沒有代碼),請添加日誌貓和更多代碼,以便我們可以幫助 – 2012-03-24 09:29:14

+0

mDbHelper = new ScoresDbAdapter(本); mDbHelper.open(); 也記住我使用相同的命令(fetchNote)以另一種方法從數據庫中讀取,所以它運行良好,極有可能。 – Zephyer 2012-03-24 09:43:05

回答

0

另外的代碼你有,你可以做這樣的事情

String selectQuery = "SELECT MAX(COLUMN_NAME) FROM " + TABLE_NAME; 
SQLiteDatabase db = this.getWritableDatabase(); 
Cursor cursor = db.rawQuery(selectQuery, null); 
if(cursor.moveToFirst(){ 
    rowScore = Integer.parseInt(cursor.getString(0); 
    if(rowScore < currentScore){ 
     //you have a new high score 
    } 
} 

這種方式,您採取的附帶的SQLite這是速度更快,節省自己的一些工作中的預定義的功能優勢。