In Android SQLite, working directly with Cursor is more memory efficient than creating Model Objects?

1.1k views Asked by At

In most of the Android sample codes, populating a ListView from SQLite database is done in two ways,

  1. Prefetch data to List - Execute query, create Model objects for each row then add it to a List and close the Cursor, then populate ListView with List.

  2. Without List and Model objects - Execute query and populate ListView by following the Cursor using moveToFirst, moveToLast, move, as required.

Now I want to know, which of the above method is more memory efficient, in Android ?

2

There are 2 answers

2
Ridcully On BEST ANSWER

The Cursor approach is more memory efficient:

Suppose you have 1000 entries in your database and you have a ListView which can show 10 entries at the same time. If you create a list at first, you'll have to create 1000 model objects (each of which in turn consists of several objects depending on the number of columns of your table) and the listview creates additional 10 views (actually some more, depending on the layout of the list) for displaying the 10 items. Now when the user scrolls the list, in your Adapter you end up copying data from your model objects to the list item views currently in view.

On the other hand, if you use a CursorAdapter, whenever you have to fill a list item with data, you are provided with the Cursor holding exactly the data for that row and you can simply pick the data of the columns you actually need to be displayed in the list item. No need for creating the 1000 model objects.

From a code readability perspective, a model approach would be better because working with Cursors is quite low level, you'll need to know the names of the columns in the database and so on.

6
Blaze Tama On

I think you need to use Service or at least Thread/Async so your UI thread will not be blocked. Service is better because people can go to other apps while downloading. You can use BroadcastReceiver to communicate with your running Service.