A simple way to populate an Android ListView with a SQLite database Cursor

Here’s an example of how to populate an Android ListView, where I get the data for the ListView from a database Cursor:

DatabaseHelper.TeamsCursor tc = DatabaseManager.get(getActivity()).getAllTeams();
ArrayList<String> listOfTeamNames = new ArrayList<>();
for(tc.moveToFirst(); !tc.isAfterLast(); tc.moveToNext()) {

// list the team names with an adapter that talks to our listview
TeamNamesAdapter adapter = new TeamNamesAdapter(listOfTeamNames);

There are more formal ways to create an adapter class to work with a Cursor, but for my needs I just needed to get a list of names from a SQLite database table and show them in a simple ListView — part of a ListFragment — and this was the simplest code to write.

FWIW, the example also shows one way to iterate over the elements in a Cursor using a Java for loop.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.