Friday, May 28, 2010

Iterate over the address book pulling out names, locations, and phone numbers


A less publicized feature of Android is the ability to share content between applications. We're going to use this feature to populate our List with our contacts' names and their current distance from our phone so we create an updateList method that we call after we've gotten our current location.
Use the ContentResolver to return a query that provides access to data shared using Content Providers. Queries are returned ascursors that provide access to the underlying data tables. The data we're interested in is accessed using the People content provider.
    Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null); startManagingCursor(c);
The Cursor is a managed way of controlling your position (Row) in the underlying table. We get access to the data by specifying the column that holds the information we're after. Rather than memorising the column index for each Content Provider we can use constants from the People class as a shortcut.
    int coordIdx = c.getColumnIndex(People.NOTES); int phoneIdx = c.getColumnIndex(People.PhonesColumns.NUMBER); int nameIdx = c.getColumnIndex(People.NAME);
Now iterate over the table using the cursor storing the results in arrays. You'll note that we're pulling our contacts' location from theNotes field. In reality we'd want to figure this out based on their address using a geocoding lookup.
    List listItems = new ArrayList(); c.first(); do {
      String name = c.getString(nameIdx); String coords = c.getString(coordIdx); String phone = c.getString(phoneIdx); ... [ Process the lat/long from the coordinates ] ... ... [ Storing their location under variable loc ] ... String distStr = String.valueOf(location.distanceTo(loc)/1000); name = name + " (" + distStr + "km)"; listItems.add(name); numbers.add("tel:" + phone);
    } while(c.next());
Then we assign our list of strings to the array using an ArrayAdapter.
    ArrayAdapter notes = new ArrayAdapter(this, R.layout.notes_row, items); setListAdapter(notes);

No comments:

Post a Comment