First a warning. Try all the code out on an emulator first. The methods below will completely wipe the contacts from your device so you'll want to make sure the backup step works first before continuing. You've been warned!
Anyway, if you want to backup the contacts on your device to a file you'd use the following process:
- Find all the contacts
- Request a file system object
- Create a FileEntry object
- Create a FileWriter
- Write the JSON data to file
Next we will delete all the contacts on the device. The steps are:
- Find all the contacts
- Recurse through the contacts deleting one at a time.
The code looks like:
This might look a little bit weird at first glance but trust me it'll make sense. You'll notice in deleteAllTheContacts the first thing we do is to create a local function called deleteContacts. This is the method that will actually remove the contacts from the device. Then after the definition of deleteContacts we call navigator.contacts.find(). This call will get an array of all the contacts on the device and call it's success function which is deleteContacts.
Now in deleteContacts we do a check to see if the length of the contacts array is zero. If it is zero then we are done, there are no more contacts left to be deleted. If the contact array length is greater than zero we have more work to do. We'll pop the next Contact object off of the contacts array, which reduces the size of the array by one and we'll call the remove method of the Contact object. The success call back for remove method is the deleteContacts method. Keep reading this paragraph until all of your contacts have been deleted. Boom recursion.
Finally you'll want to be able to restore the contacts you've previously saved to file. I've broken it down into two separate methods to make it easier to read:
- Request local file system
- Get the FileEntry
- Request the File object
- Read the data and parse it to JSON
- Recurse through all the contacts and save them to the device
This is pretty much just unrolling the two previous steps of backing up and deleting the contacts. If you've gotten this far you should be able to understand what is going on. Although there are two lines I want to draw your attention to:
contactData.id = null;What I'm doing here is removing the unique ID's from the contact. If you skip this step you will signal the API that you are attempting to modify an existing contact and the save will most probably fail. Hopefully this helps a bunch of folks.
contactData.rawId = null;