32

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Cris
  • 12,124
  • 27
  • 92
  • 159
  • maybe this could help http://stackoverflow.com/questions/8532427/how-do-i-close-the-cursor-and-database-safely – Majid May 11 '13 at 14:30

2 Answers2

21

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.

DeRagan
  • 22,827
  • 6
  • 41
  • 50
  • where to add this line youradaptername.notifyDataSetChanged();? oncreate() or setitemclicklistener? – Metalhead1247 May 31 '13 at 14:15
  • notifyDataSetChanged() needs to be called at a point wherein you know that data in your adapter has changed. This will force the listview to redraw its views which in turn helps you to see the new data in the list. Where you are going to invoke notifyDataSetChanged() depends on your need. Example refer to thispost http://stackoverflow.com/questions/16441298/android-call-notifydatasetchanged-from-asynctask – DeRagan May 31 '13 at 14:36
6

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 ...
KishuDroid
  • 5,411
  • 4
  • 30
  • 47
Muhammad Shahab
  • 4,187
  • 4
  • 34
  • 44
  • 8
    It's always good practice to wrap your cursor.close() in a finally clause. This way you make sure your cursor is closed, no matter if a RuntimeException is thrown during processing. – schnatterer Jul 28 '13 at 13:30