Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to close cursor in Android?

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.

like image 415
Cris Avatar asked Nov 08 '10 11:11

Cris


People also ask

When should I close a cursor?

A cursor should be closed when it is no longer needed. Every non-holdable open cursor is implicitly closed when a transaction is terminated by COMMIT or ROLLBACK . A holdable cursor is implicitly closed if the transaction that created it aborts via ROLLBACK .

Why do we close the cursor?

Yes, it's recommended to close the cursor when you are done using that cursor object so that cursor can do whatever house keeping work it wants to do upon closure. Save this answer. Show activity on this post. Save this answer.

What is the use of cursor in Android?

Introduction to Cursor in Android The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory. Here, we pass the table name, column name only then we receive the cursor.


1 Answers

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.

like image 193
DeRagan Avatar answered Sep 30 '22 05:09

DeRagan