如何解决close()从未在数据库错误上显式调用

时间:2014-03-02 08:20:19

标签: android sqlite

我在这里和其他博客上都经历了很多答案。他们建议我在所有打开的连接上调用close()函数。我做了但仍然得到这个错误。我有一个应用程序,首先尝试计算sqlite数据库表中存在的提示数,如果没有行返回0.如果有任何行,则返回行数。这是我的代码

public int count_tips() {

    Cursor cursor = ourDatabase.rawQuery("select * from "
            + DATABASE_TIPS_TABLE, null);

    if (cursor != null) {
        cursor.moveToFirst();
        if (cursor.getInt(0) == 0) {

            cursor.close();
            return 0;
        } else {

            cursor.close();
            return cursor.getCount();
        }
    } else {
        cursor.close();
    }

    return 0;

}

但我一直收到下面的错误,可能会出错。至少我想我已经关闭了我打开的所有数据库连接。但无法弄清楚哪里出错了。

03-02 11:09:00.457: D/Cursor(4712): Table name   : null
03-02 11:09:00.457: D/Cursor(4712): SQL          : SQLiteQuery: select * from tips
03-02 11:09:00.457: I/dalvikvm(4712): Uncaught exception thrown by finalizer (will be discarded):
03-02 11:09:00.457: I/dalvikvm(4712): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor@4054c690 on null that has not been deactivated or closed
03-02 11:09:00.464: I/dalvikvm(4712):   at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:620)
03-02 11:09:00.464: I/dalvikvm(4712):   at dalvik.system.NativeStart.run(Native Method)
03-02 11:09:00.472: E/Database(4712): close() was never explicitly called on database '/data/data/com.jingo.willappsug.yamba/databases/yambasqlite' 
03-02 11:09:00.472: E/Database(4712): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
03-02 11:09:00.472: E/Database(4712):   at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1847)

1 个答案:

答案 0 :(得分:3)

您是否尝试将close()来电置于finally阻止try/catch

public int count_tips() {
   try {
       ... // your code here
   }
   catch (Exception e) {
       // handle the exception properly
   }
   finally {
       cursor.close()
   }
}