20 - Phonegap Contacts Retrieving

Introduction

Just saving the contact details in the contacts database of your device might not be useful. You might be able to retrieve the details as you want. The Contacts API of PhoneGap offers a find method which allows you to search for the required details in the contacts database of the device.

Create an App to Retrieve Contacts

Suppose we want to send birthday messages to our contacts on their birthday. We are going to develop an app that displays the birthday and email id of all the contacts we have in our mobile phone. Before proceeding with this app, add a number of contacts using the app we have created in the previous tutorial, that is Contacts - Storing. Make sure that you have enough number of contacts so that we can search using the characters in their names.

Create a mobile app for iOS platform named iOSGetContacts. Once the project is created on the desktop, open the folder and double click the iOSGetContacts.xcodeproj icon to launch the project in the XCode environment. Again go back to the project folder on the desktop, open the index.html file inside the www folder using your favourite text editor and clean it up.

We are going to search the name. As soon as the user enters a character in a textbox, all the names that contain the specific character will be displayed in a table with their corresponding email and date of birth. So, we need a textbox for the user to enter the search criteria. We also need a <div> element to display the result.

Add the following line inside the <body> tag.

Search By Name:<input type="text" id="searchCriteria" /><br />
        <div id="result"></div>

Add the following lines of code inside the <head> section to check whether the device is ready. Once the device is ready, we will add the event listener for the keyup event of the textbox. This makes sure that as soon as a character is entered in the textbox, the matching details will be displayed.

<script>
       window.onload = function()
       {
          document.addEventListener("deviceready", init, false);
       }
       function init()
       {
          document.getElementById("searchCriteria").addEventListener('keyup', searchContacts, false);
       }
</script>

Next we need to write the searchContacts function. We are going to use the find method of the contacts object to search for the details. The find method will return an array of Contacts objects, each object containing the specified fields. The find method has four parameters. The first parameter specifies the fields that are to be searched. Also, only the fields specified in the first parameter will be returned as properties of Contacts object as the result. If you do not set any value to the first parameter, the resulting Contacts array will only contain the id value. If you set the value as ['*"], then all the contact fields will be returned.

The second and third parameters are call back functions in case of success and failure respectively. The success call back function will return the array of contacts object as its parameter. The fourth parameter is an optional parameter of type contactFindOptions that customizes the search. You can set the value of filter to the search string used to search contacts and set the value of multiple to true if you want to get all the matching contacts (in case of many).

Add the following lines of code after the init function inside the <script> section.

function searchContacts()
{
     var searchValue = document.getElementById(searchCriteria).value;
     var searchFields = ["name", "emails", "birthday"];
     var searchOptions = new ContactFindOptions();
     searchOptions.filter = searchValue;
     searchOptions.multiple = true;
     navigator.contacts.find(searchFields, onSuccess, onError, searchOptions);
}

We first collected the search criteria into a local variable. We specified the fields that are to be searched during the search and also to be returned as properties after search. We want to search the name field for the characters entered by the user and we want to display the email and birthday details. The parameters specified inside the array are the property names of Contact object. That is, you cannot specify “email” instead of “emails” as emails is the property name of Contact object.

Then, we have created an object named searchOptions of type ContactFindOptions and set the value of filter to the value entered by the user (search criteria) and value of multiple to true as we want to get all matching records. Next we have passed these parameters to the find method.

Next we need to write the onSuccess and onError function. The Contacts object returned by the onSuccess callback function will return all the details. We just need to grab them and display them in the format we want. Add the following lines of code inside the <script> section.

function onSuccess(contacts)
{
     document.getElementById('result').innerHTML ="";
     if (document.getElementById("searchCriteria").value != "")
      {
           if (contacts.length>0)
           {                   
                var birthday, convertedDate, formattedDate;
                output = "<table border='1px'><tr><th>Name</th><th>Email</th><th>Birthday</th></tr>";
                for(var x=0; x< contacts.length; x++)
                {
                      birthday = contacts[x].birthday;
                      convertedDate = new Date(birthday);
                      formattedDate = convertedDate.getDate() + "-" + convertedDate.getMonth() + "-" + convertedDate.getFullYear();
                      output += "<tr><td>" +  contacts[x].name.givenName + " " + contacts[x].name.familyName
                                 + "</td><td>" +  contacts[x].emails[0].value
                                 + "</td><td>" + formattedDate + "</td></tr>";
                }
               output += "</table>";
           }
           else
                    output = "No Matching Records!!!";
           document.getElementById('result').innerHTML = output;
}
function onError(error)
{
        alert("Search Error" + error.code);
}

First of all, we have cleared the content in the <div> element because otherwise it might append the result again and again. Next, we will be able to display the details only if there are matching records. That is why we have checked whether the contacts.length (number of records in contacts array) is greater than 0. If so, we will process the output. Otherwise, we will display a message, no matching records. The contacts is the array of objects returned by the success call back function.

To display the result in a table format, we first added the headers for the table. Next we need to get the name, email id and date of birth for each matching record. So we loop through the contacts array and display the details in the required format. To display the name, we append first name and last name in the name object as contacts[x].name.givenName + " " + contacts[x].name.familyName. We will get the email id from the emails array using contacts[x].emails[0].value. The value returned by the birthday property of Contact object will return the date in milliseconds between midnight of January 1, 1970 and the birthday date. So, we have to process it the way you want. To display the date in DD-MM-YYYY format, we have made some processing to the birthday information.

Save the index.html file. Run the project and you will get a screen with a textbox to enter the search criteria. Enter any character between a to z and you will find all the names that contain the specified character with the corresponding email and date of birth information. For example, if your database contains a contact named Sarah White, as soon as you enter w in the textbox, you will see this output (of course, the values could be different).

out1.png

If you have more than one matching contacts, then the details will be displayed as follows:

out3.png

The characters need not be in the beginning itself as in the previous case. It can be anywhere in the names field.

out2.png

If you enter a character that is not matching any names, then the output will be as follows.

Screen Shot 2014-10-21 at 6.23.03 PM.png

Summary

In this tutorial, we have created an app that allows you to search for contacts by name and then display the fields we want. We have displayed the information in tabular format. When designing apps, you can display the fields we want in any format.

Like us on Facebook