When to close cursor in Android?

Cris picture Cris · Nov 8, 2010 · Viewed 29.4k times · Source

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

Answer

DeRagan picture DeRagan · Nov 8, 2010

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.