When to close cursor in Android?

安稳与你 提交于 2019-12-09 07:32:12

问题


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


来源:https://stackoverflow.com/questions/4123317/when-to-close-cursor-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!