游标在没有事先close()Android的情况下完成

时间:2012-05-03 15:19:15

标签: android sqlite sqliteopenhelper

在我的应用程序中,我有一个listview。我通过SQLiteDatabase中的查询获取数据。当我从db获取数据时,我收到此错误: error

当我从第20行到第21行时发生。 occur

我尝试将cursor.deactivate()和cursor.close()放在regel 50上。但没有结果。任何人都知道为什么我会得到这个错误以及如何解决它?谢谢:))

4 个答案:

答案 0 :(得分:25)

您必须在数据库之前关闭光标。将代码放在try / catch块和finally块中,关闭光标,然后关闭数据库:

try {
    db = ...
} catch(Exception ex) { 
    // Log the exception's message or whatever you like
} finally {
    try {
      if( cursor != null && !cursor.isClosed())
        cursor.close();
       if( db.isOpen() )
        db.close();
    } catch(Exception ex) {}
}

在使用DB或内容提供商进行IO时,关闭序列非常重要。 有关更多信息,请参阅this link

答案 1 :(得分:10)

找到这样的问题只需启用StrictMode for Debug Version:

public void onCreate() {
     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }
     super.onCreate();
 }

更多信息@ http://developer.android.com/reference/android/os/StrictMode.html

一切顺利,

答案 2 :(得分:4)

始终,请记住在关闭数据库之前通过调用cursor.close()来关闭游标。这应该可以解决你的问题。

答案 3 :(得分:0)

让活动使用startManagingCursor(c)生命周期地管理游标,这样就可以了。