Android error - close() was never explicitly called on database

前端 未结 3 1323
说谎
说谎 2020-11-27 13:47

Where should I call close() on the code?

The LogCat returns this error:

close() was never explicitly called on database android.database.sql

相关标签:
3条回答
  • 2020-11-27 14:01

    I suspect fillList() is called multiple times during a RatedCalls "session". So each time you create a new Cursor instance and call startManagingCursor() on it. Doing so you accumulate a list of Cursors - ArrayList<ManagedCursor> to be precise that is declared in ListActivity. Normally they (cursors that are being managed) will be closed automatically in ListActivity.onDestroy(). Could you confirm your RatedCalls actually passes onDestroy().

    Do you override somehow the ListActivity.onDestroy() in RatedCalls. If yes, then do you call super.onDestroy() (you should call it) ?

    I don't get the purpose of calling onStop() in RatedCallsContentObserver.onChange() after the fillList();. I believe Activity life-cycle callbacks should be called by OS only. So maybe calling a life-cycle callback manually you somehow prevent from onDestroy() to be called by OS (just a guess)?

    UPDATE:

    Dan Breslau is right - it's db object that is not closed. Sorry for misleading.

    0 讨论(0)
  • 2020-11-27 14:08

    Literally understand database is not normally closed, the actual because repeated instantiation your database, or connect you have been set up, and you and try to open another connection there will be no exception. So the solution is, make sure that you open only a connection.

    0 讨论(0)
  • 2020-11-27 14:19

    I think the problem is that you need to close the db when your activity is destroyed. Try adding this to your activity:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (openHelper != null) {
            openHelper.close();
        }
        if (cdh != null) {
            cdh.close();
        }
    }
    

    and add this to your CallDataHelper class:

    public void close() {
        // NOTE: openHelper must now be a member of CallDataHelper;
        // you currently have it as a local in your constructor
        if (openHelper != null) {
            openHelper.close();
        }
    }
    

    EDIT 2: Also change the CallDataHelper constructor to:

    // Declare openHelper as a member variable
    OpenHelper openHelper = null;
    
    public CallDataHelper(Context context) {
        this.context = context;
        openHelper = new OpenHelper(this.context);
        this.db = openHelper.getWritableDatabase();
    }
    

    This should successfully close the database connection that was created by both of your OpenHelper instances.

    ( EDITED to reflect the fact that you use two OpenHelper instances.)

    0 讨论(0)
提交回复
热议问题