Home » Android » When to close cursor in Android?

When to close cursor in Android?

Posted by: admin April 23, 2020 Leave a comment


I have an app that uses cursor to select data via rawQuery from a sqlite db to populate a ListView in Android;. Every time the user clicks on a listview item I create a new instance of Activity to re-populate listview. Is it better to call cursor.close() and db.close() to avoid memory problems? I actually have db.close() in OnDestroy() of my activity.

How to&Answers:

You can close the cursor once you have retrieved the values for that particular object inside your method.

btw…You don’t have to recreate a listview every time for a user click event. Just notify that there is some change in data of your adapter that has been set on the listview.

Something like


This should repopulate contents inside ur listview automatically.


Well if you are creating a new instance every time of the same Activity (though I am not sure its a good programming practice). You can close the cursor as soon as your have finished traversing / iterating through the source of the listview.


A sample implementation would be something like

//Pre cursor code
if (cursor.moveToFirst()) {
    do {
        if (cursor.getString(0).equals(value)) {
            a = true;
            return a;
    } while (cursor.moveToNext());

//Close cursor here, when its work is complete

//Post cursor code ...