Joe Ng
Joe Ng

Reputation: 91

When not to use CursorAdapter for ListView

I've heard from my friend that CursorAdapter does not follow the MVC rule, it take the values directly from Database to the View, not through the Model. Furthermore, he said everytime user iterate items via list view, CursorAdapter execute dbs query again and again. As a result, CursorAdapter will not be used frequently. I'm very curious about this statement, anyone can help me out? Is he right or wrong? And if he is right, what Adapter I can use instead?

Upvotes: 0

Views: 91

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006869

CursorAdapter... take the values directly from Database to the View, not through the Model

That depends on what you define your model to be. The Cursor could be the model, for trivial apps, in which case CursorAdapter takes data from the model and applies it to the view.

Your friend may be thinking of a model defined as a set of custom Java classes; in that case, CursorAdapter would know nothing about those classes.

he said everytime user iterate items via list view, CursorAdapter execute dbs query again and again

Not really. CursorAdapter knows nothing about executing database queries.

The only scenario that I can think of that resembles what you friend describes is if your query has a large result set, over 1MB. In that case, the Cursor will not hold the entire result set, the way it normally does. Instead, it holds a portion of the results, and if the user scrolls past what the Cursor holds, the Cursor will trigger database I/O to fetch more results (and let go of some past ones, to minimize the overall amount of memory held by the Cursor).

As a result, CursorAdapter will not be used frequently

I would say that it is less frequently used than is ArrayAdapter, and both are falling out of favor in general, as more developers move to RecyclerView and RecyclerView.Adapter.

I think what your friend really is concerned about is using a Cursor as a model, as opposed to having a "real" model (and perhaps view-models) as part of an MVC/MVP/MVVM architecture. Certainly what I hear from larger projects indicates that a Cursor is mostly used for populating other model objects, rather than being used by a CursorAdapter or RecyclerView.Adapter directly. But, it really depends a lot on the app. Trivial apps do not need strict adherence to some specific GUI architecture, and the dividing line between "trivial apps" and "larger projects" is difficult to define.

And if he is right, what Adapter I can use instead?

If your friend wants model Java objects, typically you would use an ArrayAdapter or a BaseAdapter that knows how to get at the collection of model objects. Or, in the RecyclerView realm, you would use a RecyclerView.Adapter that knows about the structure of your collection of model objects.

Upvotes: 1

Related Questions