Skip to content

February 8, 2012

1

Deal with contacts cross-platform (part 1)

by nady

This tutorials shows you how to use mobile phone contact lists with PhoneGap.

The main objectives of this first part of the tutorial are:

  • get the device contacts using Phonegap Contacts
  • list the contacts using jQuery Mobile List Views

Final result:

use mobile phone contact lists with phonegap

Download Sources

In order to setup your new project and get started follow this basic cross-platform mobile app tutorial.
Find out more about Notifications & Buttons.

First of all let’s create the view for the contacts that will be listed.

[html]
<div data-role="page">
<div data-role="header" data-position="fixed">
<h1>DigitalNoiz</h1>
</div>
<div data-role="content">
<h2>Contacts List</h2>
</div>
</div>
[/html]

To create the list view use <ul> tag or <ol> tag for numbered list with attribute data-role="listview".
Inside we have <li> tags with an anchor, when there’s a tap on a list item a click is triggered on the anchor that makes the transition to that URL.
Add into content:

[html]
<ul id="allContacts" data-role="listview">
<li><a href="#">AContact</a></li>
<li><a href="#">BContact</a></li>
<li><a href="#">CContact</a></li>
<li><a href="#">DContact</a></li>
</ul>
[/html]

When the list is in a page where there are and other types of content, the list can be put into a block that will add some margin and round corner, do this by adding data-inset="true".
jQuery Mobile framework provides a easy way to filter data from the list using a search box above the list and, as the user types, it shows only the items that contain the search string, add data-filter="true".

[html]
<ul id="allContacts" data-role="listview" data-filter="true" data-inset="true">
[/html]

Because we will list contacts let’s divide the list alphabetically, add a new list item with attribute data-role="list-divider" for every letter.

[html]
<ul id="allContacts" data-role="listview" data-filter="true" data-inset="true">
<li data-role="list-divider">A</li>
<li><a href="#">AContact</a></li>
<li data-role="list-divider">B</li>
<li><a href="#">BContact</a></li>
<li data-role="list-divider">C</li>
<li><a href="#">CContact</a></li>
<li data-role="list-divider">D</li>
<li><a href="#">DContact</a></li>
</ul>
[/html]

You could add thumbnails to a list item by adding an image inside the list item, that will be resized to 80×80 px. This could be useful if you want to add a picture for the contact. You can also add an 16×16 px icon by adding class="ui-li-icon". In www create img folder and add your images there, we have an icon contactIcon.png

[html]
<ul id="allContacts" data-role="listview" data-filter="true" data-inset="true">
<li data-role="list-divider">A</li>
<li>
<a href="#">
<img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />
AContact
</a>
</li>
<li data-role="list-divider">B</li>
<li>
<a href="#">
<img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />
BContact
</a>
</li>
<li data-role="list-divider">C</li>
<li>
<a href="#">
<img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />
CContact
</a>
</li>
<li data-role="list-divider">D</li>
<li>
<a href="#">
<img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />
DContact
</a>
</li>
</ul>
[/html]

For the moment we have the list view that we want, now it’s time to get the contacts from the device.
Open js/script.js and create a function getContacts that will retrieve all the contacts.

[js]
// handling document ready and phonegap deviceready
window.addEventListener(‘load’, function () {
document.addEventListener(‘deviceready’, onDeviceReady, false);
}, false);

// Phonegap is loaded and can be used
function onDeviceReady(){
getContacts();
}

/* get all contacts from device */
function getContacts(){
var optFilter = new ContactFindOptions();
optFilter.filter = ""; // to return all contacts
optFilter.multiple = true; // return multiple results
fields = ["name"];

// get all contacts
navigator.contacts.find(fields, gcsSuccess, gcsError, optFilter);
}
[/js]

Calling navigator.contacts.find function returns an array of Contact object that is passed to the callback function gcsSuccess. This object contains properties that describes a contact.

Contact properties:

id – unique identifier (DOMString)
displayName – the name of the contact (DOMString)
name – object that contains details of a persons name (ContactName)
nickname – a casual name for the contact (DOMString)
phoneNumbers – an array with all the phone numbers (ContactField[])
emails – an array with all the emails (ContactField[])
addresses – an array with all the addresses (ContactAddress[])
ims – an array with all the IM addresses (ContactField[])
organizations – an array with all the organizations (ContactOrganization[])
birthday – the birthday of the contact (Date)
note – a note about the contact (DOMString)
photos – an array of the contact’s photos (ContactField[])
categories – an array with the user defined categories (ContactField[])
urls – an array of all the web pages of the contact (ContactField[])

ContactName properties:

formatted – the complete name (DOMString)
familyName – contacts family name (DOMString)
givenName – contacts given name (DOMString)
middleName – contacts middle name (DOMString)
honorificPrefix – contacts prefix, eg. Mr. or Dr. (DOMString)
honorificSuffix – contacts suffix (DOMString)

ContactField properties:

type – tells you what type of field this is, eg. “home” (DOMString)
value – the value of the field, like phone number or url address (DOMString)
pref – set to true if it’s preferred value (Boolean)

ContactAddress properties:

pref – set to true if it’s preferred address (Boolean)
type – tells you what type of field this is, eg. “home” (DOMString)
formatted – the full address formatted for display (DOMString)
streetAddress – the full street address (DOMString)
locality – the city or locality (DOMString)
region – the state or region (DOMString)
postalCode – the posta code or zip code (DOMString)
country – the country (DOMString)

ContactOrganisation properties:

pref – set to true if it’s preferred organisation (Boolean)
type – tells you what type of field this is, eg. “home” (DOMString)
name – the name of the organisation (DOMString)
departament – the departament where the contact works (DOMString)
title – the contacts title at the organisation (DOMString)

Not all of the above properties are supported on every device platform, those properties that are highlighted with green are most safe to use cross-platform.

In this line navigator.contacts.find(fields, gcsSuccess, gcsError, optFilter) the parameter fields must specify which fields to be returned into the Contact object, in our case it will return only the name field. If this doesn’t specify any field it will return only the id field, to return all fields use fields = ["*"] . The gcsSuccess is the callback function that runs on find success and takes as parameter the contacts array, gcsError is the callback function that runs when an error occurs. To filter the contacts use optFilter that is a ContactFindOptions object.

Now following our tutorial that shows you how to use mobile phone contact lists with PhoneGap we will describe ContactFindOptions.

ContactFindOptions properties:

filter – the search string to find contacts (DOMString)
multiple – determine if it should return multiple contacts (Boolean)

Let’s add the callback functions for find success and error.

[js]
/* get all contacts success */
function gcsSuccess(contacts){
if( contacts.length != 0 ){
// we have the contacts
} else $(‘#allContacts’).html(‘No contacts’);
}

/* get all contacts error */
function gcsError(contactError){
navigator.notification.alert(‘Contacts Error’);
}
[/js]

Because I want to list the contacts in alphabetic order I put the name of the contacts in an array that I sort and as I iterate the array and list the items, whenever the first letter is not the same as it was in the previous items I add a new divider. For the changes to take place the listview must be refreshed.

[js]
function gcsSuccess(contacts){
if( contacts.length != 0 ){
// get formatted names and sort
var names = new Array();
for(var i=0; i<contacts.length; ++i){
if(contacts[i].name){
if(contacts[i].name.formatted) names.push(contacts[i].name.formatted);
}
}
names.sort();

var list = $(‘#allContacts’); // list to put contacts
list.html(”); // remove all the list items
var divider = names[0][0]; // first divider letter
for(var i=0; i<names.length; ++i){
if( divider != names[i][0] ) { // add a new divider
divider = names[i][0];
list.append(‘<li data-role="list-divider">’ + divider + ‘</li>’);
list.append(‘<li><a href="#"><img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />’ + names[i] + ‘</a></li>’);
} else {
if( i == 0 ) list.append(‘<li data-role="list-divider">’ + divider + ‘</li>’);
list.append(‘<li><a href="#"><img src="img/contactIcon.png" class="ui-li-icon" alt="Contact" />’ + names[i] + ‘</a></li>’);
}
}

list.listview(‘refresh’); // refresh the list view
} else $(‘#allContacts’).html(‘No contacts’);
}
[/js]

Now you can remove the sample list items that we created in the beginning of this tutorial.

This is it! You’ve learn how to use mobile phone contact lists with PhoneGap

In the second part of the tutorial (see next post) we will learn how to add, edit and delete a contact and how to use jQuery Mobile form elements.

This concludes first part of our tutorial that shows you how to use mobile phone contact lists with PhoneGap.

Read more from Mobile

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments