2012-09-04 31 views
0

在你問我之前,我已經四處尋找解決我的問題,我不能自己工作,因此來找你們。SQLIte光標 - 在null上完成還沒有被停用或關閉的例外

的問題

我有我的光標未捕獲的異常問題,我不能工作了....

錯誤

09-04 15:48:38.863: I/dalvikvm(1421): Uncaught exception thrown by finalizer (will be discarded): 
09-04 15:48:38.863: I/dalvikvm(1421): Ljava/lang/IllegalStateException;: Finalizing cursor [email protected] on null that has not been deactivated or closed 
09-04 15:48:38.863: I/dalvikvm(1421): at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596) 
09-04 15:48:38.873: I/dalvikvm(1421): at dalvik.system.NativeStart.run(Native Method) 

代碼,它的抱怨關於

public CCTrackLocation getTrackLocationForID(int id) { 
     CCTrackLocation trackLocation = new CCTrackLocation(); 

     String selectQuery = "SELECT * FROM "+TABLE_TRACK_LOCATION+" WHERE \"id\" = "+ String.valueOf(id); 

     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(selectQuery,null); 
     if (cursor.moveToFirst()) { 
      do { 
       trackLocation.setID(cursor.getInt(0)); 
       trackLocation.segmentID = cursor.getInt(1); 
       trackLocation.timestamp = cursor.getDouble(2); 
       trackLocation.latitude = cursor.getDouble(3); 
       trackLocation.longitude = cursor.getDouble(4); 
       trackLocation.altitude = cursor.getDouble(5); 
       trackLocation.velocity = cursor.getDouble(6); 
       trackLocation.heading = cursor.getDouble(7); 
       trackLocation.haccuracy = cursor.getDouble(8); 
       trackLocation.vaccuracy = cursor.getDouble(9); 
      }while(cursor.moveToNext()); 
     } 

     cursor.close(); 
     db.close(); 

     return trackLocation; 
    } 

任何幫助將非常感激。

回答

0

要解決這個問題,這裏是我所做的。

  1. 只打開和關閉數據庫一次。即使我每次使用它都打開和關閉數據庫,有時候我覺得不夠快,因此我得到了錯誤。
  2. 每次使用完光標後關閉光標。這對問題進行了排序。
0

爲了安全起見,將所有數據庫代碼放在try/catch/finally子句中,並將cursor.close()和db.close()移動到它的finally部分,以確保您正在關閉遊標和db,即使之前拋出異常