When to close cursor in Android?

2019-03-22 14:40发布

问题:

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.

回答1:

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

youradaptername.notifyDataSetChanged();

This should repopulate contents inside ur listview automatically.



回答2:

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.

Example:

A sample implementation would be something like

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

//Close cursor here, when its work is complete
cursor.close();

//Post cursor code ...