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

Tim*_*vos 19 sqlite android sqliteopenhelper

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

当我从第20行到第21行时发生. 发生

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

Ali*_*jad 25

您必须在数据库之前关闭光标.将代码放在try/ catchblock和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) {}
}
Run Code Online (Sandbox Code Playgroud)

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


cV2*_*cV2 11

要找到这样的问题,只需启用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();
 }
Run Code Online (Sandbox Code Playgroud)

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

祝一切顺利,