开发者

When to close cursor in Android?

开发者 https://www.devze.com 2023-01-24 03:58 出处:网络
I have an app that uses a cursor to select data via rawQuery from an SQLite DB to populate a ListView in Android. Every time the user clicks on a listview item I create a new instance of Activity t开发

I have an app that uses a cursor to select data via rawQuery from an SQLite DB to populate a ListView in Android. Every time the user clicks on a listview item I create a new instance of Activity t开发者_StackOverflowo 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.


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.


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 ...
0

精彩评论

暂无评论...
验证码 换一张
取 消