SQLIte Cursor - 在null上完成尚未停用或关闭的异常

时间:2012-09-04 14:57:40

标签: java android sqlite

在你问我之前我已经四处寻找解决问题的办法时,我自己无法解决问题,所以来找你们。

问题

我的光标有一个未被捕获的异常问题,我无法解决它....

错误

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 android.database.sqlite.SQLiteCursor@44ef6598 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;
    }

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

为了安全起见,将所有db代码放在try / catch / finally子句中,并将cursor.close()和db.close()移动到它的finally部分,以确保关闭即使在

之前抛出异常,也可以使用游标和数据库

答案 1 :(得分:0)

要解决这个问题,我就是这样做的。

  1. 仅打开和关闭数据库一次。即使我每次使用它时都打开并关闭了数据库,有时我认为它不够快,因此我得到了错误。
  2. 每次我使用它并完成它后关闭光标。这解决了这个问题。