Android Basics – Learn how to use a CursorAdapter to bind data from a Cursor to a ListView

Suppose you are using a ListView to display a list of items. And these items come from the database. To help you implement this functionality CursorAdapter comes in handy.

It is like a ListAdapter. The difference being that instead of getting data from an Array it gets from the database.

Another advantage of using CursorAdapter is that the number of items it fetches from the database is equal to the number which can be displayed on screen.

So for instance if the table has 100 rows and the app can display only 5 at a time, then CursorAdapter will get only 5 rows.

As the user scrolls it pulls more data. This makes a CursorAdapter efficient.

You will use a SimpleCursorAdapter which implements a CursorAdapter in your App. Let’s see how.

The Constructor which you will be using will look like:

public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to, int flags)

The parameter details are available in Android documentation.

“flags” will be set to 0 for demonstration purpose.

If you are using a CursorAdapter then you do not need to close the cursor and the database. You can do this in the onDestroy lifecycle method.

Source Code is available here

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: