As we said in the How-to create an Address Book in the Google Android Programming Environment - First Steps this class will be an ListActivity that implements OnItemSelectedListener
public class ContactList extends ListActivity implements OnItemSelectedListener
This OnItemSelectedListener is used to interact with every element of the list. With this, we can get the information of the contact if we click on the row where this contact is placed.
We can fill the list with information in two different ways. In our case, we are going to use Contact Providers, its more useful to work with the Method 2 (Cursor List) than the first one. Anyway, lets see both methods.
Method 1 → Static List
With this method, we have to create an ArrayAdapter class. This ArrayAdapter will be created from a ArrayList, and a widget, and will be used by the ListActivity (our class) to create and display the elements in the screen.
The constructor is that easy:
ArrayAdapter<DataType>fileList=new ArrayAdapter<DataType>(this, R.layout.row, elements);
where elements is a ArrayList, with the elements we want to add to our list. We can create an static ArrayList of elements
ArrayList<String> elements = new ArrayList<String> ();
(we are using <string> as data type, but we can use whatever we want)
and we can add strings to our ArrayList in this way:
elements.add(“Juan Ito”);
elements.add(“Bar Tolo”);
In the ArrayListAdapter we have another interesting field: R.layout.row. This is a single xml file, a textView usually. Here we can change the appearance of every row in the List. Its like to say “Every row in our list is going to be like the R.layour.row file”.
Once we have our ArrayLisAdapter, we have to attach it to the ListActivity using:
setListAdapter(fileList);
Method 2 → Cursor List
This is slightly different from the first method. Here were are going to use a Cursor as Adapter.
To retrieve this cursor:
Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
startManagingCursor(c);
Here we get the Contacts information and we store them in a Cursor. The contact URI we need to is People.CONTENT_URI.
Now, once we have it, lets create the adapter:
ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, c, new String[] {People.NAME}, new int[] {R.layout.row});
Where:
R.layout.main is the xml file where the ListView is.
c is the Cursor.
new String[] {People.NAME} this is used to say the adapter that we are going to get the column People.NAME and put it in the list.
New int[] {R.layout.row} this is like the Method 1. Just to say how rows are designed.
Finally, to add this adapter to the ListActivity, just:
setListAdapter(adapter);