Cursor finalized without prior close() Android

半腔热情 提交于 2019-12-18 12:56:07

问题


In my application I have a listview. I get my data with a query from a SQLiteDatabase. When I get the data from the db I get this error:

It occurs when I go from line 20 to 21.

I tried placing cursor.deactivate() and cursor.close() on regel 50. But with no result. Anyone knows why I get this error and how to solve it? Thanks :)


回答1:


You have to close the cursor before the database. Put your code in a try / catch block and in a finally block, close the cursor and then close the database:

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) {}
}

Closing sequence matters a lot while doing IO with DB or Content Providers. For more information refer this link




回答2:


to find such problems just enable StrictMode for Debug Version like that:

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();
 }

more information @ http://developer.android.com/reference/android/os/StrictMode.html

all the best,




回答3:


Always, remember to close the cursor by calling cursor.close() before closing the database. That should fix your problem.




回答4:


let the activity manage the cursor lifecycly by using startManagingCursor(c) and it will be fine.



来源:https://stackoverflow.com/questions/10434378/cursor-finalized-without-prior-close-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!