Search code examples
androidandroid-listviewandroid-custom-viewandroid-cursor

How do I close my Cursor when using rawQuery and CursorAdapter


I am using a rawQuery in my DB class and returning the cursor to my adapter which is a CursorAdapter which I use with a custom ListView item.

Is this cursor automatically closed after the view is painted in the screen or how to manage this cursor? what is the best practice in this scenario ?

If I close this cursor in DB class I am not able to access them from my adapter.

Thanks for your time and effort in helping me.

EDITing to add some code snippets for better understanding

This is my activity code:

calAdapter = new CalendarListAdapter(context, dbHelper.getAllCalendars());
drawerList.setAdapter(calAdapter);

This is my cursor

public Cursor getAllCalendars() {
        String query = "SELECT calendarId as _id, calendarName, calState, calShow FROM "
                + TABLE_CALENDAR_LIST;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);
        return cursor;
    }

Solution

  • You can close the old cursor after you set the new one. swapCursor() returns the old Cursor, returns null if there was not a cursor set, also returns null if you try to swap the same instance of the previously set cursor. Knowing that, you can try something like this:

    Cursor oldCursor = yourAdapter.swapCursor(newCursor);
    
    if(oldCursor != null)
        oldCursor.close();
    

    Note that when you are using a Loader (LoaderManager.LoaderCallbacks), the framework is going to close the old cursor. This is what the documentation says:

    onLoadFinished:

    The loader will release the data once it knows the application is no longer using it. For example, if the data is a cursor from a CursorLoader, you should not call close() on it yourself. ...