19 - Phonegap Contacts Storing

Introduction

It is a fact that most of the mobile phone users do not remember the contact numbers of even their near and dear ones by heart. Studies show that people fear the loss of contacts in case of mobile phone thefts more than its value. This reveals the importance of mobile phones being used as address book. We can also create apps that save and retrieve contact details using PhoneGap. The Contacts API of PhoneGap allows you to interact with the operating system of the device and save a contact in the contacts database of the device.

Create an App to Save Contacts

Create a mobile app for iOS platform named iOSCreateContacts. Once the project is created on the desktop, open the folder and double click the iOSCreateContacts.xcodeproj icon to launch the project. Now the project is opened 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 save the title, that is whether Mr, Ms or Mrs, then first name, last name, personal and office contact numbers, email address and date of birth. So we need to have input elements to collect all these inputs. We will save the details on the click of a button. So we need a button too.

Add the following line inside the <body> tag.

Title:

Title:
<select id="title">
  <option value="Mr">Mr</option>
  <option value="Mrs">Mrs</option>
  <option value="Ms">Ms</option>
</select><br />

First Name:
<input type="text" id="fName" /><br/>

Last Name:
<input type="text" id="lName" /><br/>

Phone (Home):
<input type="number" id="phoneHome" /><br/>

Phone (Office):
<input type="number" id="phoneOffice" /><br/>

Email:
<input type="text" id="email" /><br/>

Birthday:
<input type="date" id="dob" /><br />

<button id="addContact">Save Details</button>

We have created a dropdown for the title so that the user can select suitable title from the available list. Date is a new HTML5 input type which we have used for birthday.

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 click event of the button.

<script>
   window.onload = function()
   {
     document.addEventListener("deviceready", init, false);
   }
   functioninit()
   {
     document.getElementById('addContact').addEventListener("click", saveContact, false);
   }
</script>

Next we need to write the saveContact function. Inside this function, we will collect all the inputs into some local variables. Add the following lines of code after the init function inside the <script> section.

functionsaveContact()
{
  var title = document.getElementById('title').value;
  varfirstName = document.getElementById('fName').value;
  varlastName = document.getElementById('lName').value;
  varhomePhone = document.getElementById('phoneHome').value;
  varofficePhone = document.getElementById('phoneOffice').value;
  var email = document.getElementById('email').value;
  var birthday = document.getElementById('dob').value;
}

Now we need to create a Contact object. Contact object has properties like id, displayName, name, phoneNumbers, emails, addresses, organizations, birthday, photos etc to store those details. Some of the properties like name, addresses and organizations are added as separate units using objects such as ContactName, ContactAddress and ContactOrganization respectively. You can store email ids, phone numbers, IM addresses, photos, URLs etc as ContactField objects. You can store details like display name, nick name and birthday directly in the Contact object using the properties displayName, nickname and birthday respectively.

Add the following line of code at the end of the saveContact function.

       var contact = navigator.contacts.create();

The above line of code creates a Contact object using the create method. Next we will create the ContactName object and store the title, first name and last name into its suitable properties and finally add the ContactName object to the contact object we have just created. Add the following lines of code just below the above line of code:

varnameDetails = new ContactName();
nameDetails.honorificPrefix = title;
nameDetails.familyName = lastName;
nameDetails.givenName = firstName;
contact.name = nameDetails;

In the ContactName object, you can add first name, middle name, last name, formatted name, title and suffix using the properties givenName, middleName, familyName, formatted, honoricPrefix and honoricSuffix respectively. In our case, we have used only threee properties:honoricPrefix (title), givenName (first name) and familyName (last name) of the ContactName object. After adding all these values to the ContactName object (nameDetails), we set the value of name property of Contact object to nameDetails.

As mentioned already, we need to use the ContactField object to add generic fields such as emails, phone numbers, URLs, IMs, photos etc. The ContactField object has three properties: the first is the name of the item, the second is its value and the third tells whether it is user's preferred value or not (true or false). The support for these properties varies from platform to platform. So, you need to check whether the platform for which you are developing the app supports the property you want to add.

Add the following lines of code to add phone numbers and email ids to the Contact object.

varcontactNumbers = [];
contactNumbers[0] = new ContactField('home', homePhone, true);
contactNumbers[1] = new ContactField('work', officePhone, false);
contact.phoneNumbers = contactNumbers;
var emails = [];
emails[0] = new ContactField('email', email, true);
contact.emails = emails;

We have created two arrays contactNumbers and emails to store phone numbers and email id. We then create the object of ContactField type and assign it to the respective arrays. Finally we set the value of phoneNumbers and emails properties of Contact object to the contactNumbers and emails array. By setting the value of home phone number and email id true, we specify that these are user's preferred values.

We can add the birthday information directly to the Contact object by adding the following line of code.

       contact.birthday = birthday; 

Finally we have to save the Contact object. You can use the save method of the Contact object to save a new contact or update an existing contact in the contacts database of the device. Add the following line of code inside the saveContact function.

       contact.save(saveSuccess, saveError); 

Now your saveContact function will look like this:

functionsaveContact()
{
  var title = document.getElementById('title').value;
  varfirstName = document.getElementById('fName').value;
  varlastName = document.getElementById('lName').value;
  varhomePhone = document.getElementById('phoneHome').value;
  varofficePhone = document.getElementById('phoneOffice').value;
  var email = document.getElementById('email').value;
  var birthday = document.getElementById('dob').value;
  var contact = navigator.contacts.create();
  varnameDetails = new ContactName();
  nameDetails.honorificPrefix = title;
  nameDetails.familyName = lastName;
  nameDetails.givenName = firstName;
  contact.name = nameDetails;
  varcontactNumbers = [];
  contactNumbers[0] = new ContactField('home', homePhone, true);
  contactNumbers[1] = new ContactField('work', officePhone, false);
  contact.phoneNumbers = contactNumbers;
  var emails = [];
  emails[0] = new ContactField('email', email, true);
  contact.emails = emails;
  contact.birthday = birthday;
  contact.save(saveSuccess, saveError);
}

Add the following lines of code after the saveContact function.

functionsaveSuccess(contacts)
{
alert("Contact Saved Successfully!!!");
}
functionsaveError(error)
{
alert(error.code);
}

Save the index.html file and run the project from the XCode environment. Now you will get a screen like this:

out1.png

Enter the details as you want. When you try to enter the date of birth, you might get a screen like this. It is because that we have specified the input type as date.

out2.png

Once you enter all the details, your screen will look like this (Of course, the values could be different).

out3.png

Now click the Save Details button. If everything works fine, you will get a screen like this:

<p align="center> out4.png

Click the OK button. Now go to the Contacts in your emulator and you will see the contact you have added just now like this:

out5.png

The other names you see here are contacts I have created using different apps. Now click on the name you have just created and you will see the details like this:

out6.png

Of course, the phone numbers are not in correct format as these are just test values.

Summary

In this tutorial, we have created an app that allows you to store contact details on the click of a button. You can even store photos, organization details etc if you want using the suitable properties and objects of the Contact object. You can also create an app that allows users to edit the contacts details.

Like us on Facebook