By Alvin Alexander. Last updated: January 26, 2017
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()) { listOfTeamNames.add(tc.getTeam().teamName); } // list the team names with an adapter that talks to our listview TeamNamesAdapter adapter = new TeamNamesAdapter(listOfTeamNames); setListAdapter(adapter);
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.