Search Wikipedia

Search results

May 1, 2014

Working With Android Contacts (Part 1)

Introduction To Android Contacts

Learn to work with the Android contacts database. Basic knowledge of accessing SQLite in Android along with using Cursors is expected. See the Android SQLite and Cursor Article for more information. Google changed the contacts database moving from 1.x to 2.0 versions of Android. This tutorial will be broken into 2 sections. First covering accessing contacts in Android 2.0 and  Android 1.6 & before. Third we'll glue it all together with a class that abstracts specific classes for each version and a set of classes to manage the data from the contact records for that tutorial click here.

API For 1.6 and Before

Granting Access
Before an application can query the contact records access must be granted through the AndroidManifest.xml file stored in the root of the project. Add the following uses-permission belows the uses-sdk statement. 
<uses-permission android:name="android.permission.READ_CONTACTS" />
Querying the contact database
Retrieving Contact Details
Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 1.x to query the base contact records the URI to query is stored in People.CONTENT_URI. 
package com.kais.TestContacts;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(People.CONTENT_URI, 
   null, null, null, null);
        if (cur.getCount() > 0) {
      while (cur.moveToNext()) {
          String id = cur.getString(cur.getColumnIndex(People._ID));
          String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
      }
        }
    }
}
Start off with the standard view loading. Then we create a ContentResolver instance that will be used to query the SQLite database that stores the contacts. The ContentResolver query returns a Cursor instance that holds the contact records queried from the database. Then take the ID field from the contact record and store it in the string id and take the DISPLAY_NAME field and place it in the string name. For more information about cursors see the Android Cursor Tutorial.

Phone Numbers
Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable Contacts.Phones.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact.

if (Integer.parseInt(cur.getString(
            cur.getColumnIndex(People.PRIMARY_PHONE_ID))) > 0) {
  Cursor pCur = cr.query(
    Contacts.Phones.CONTENT_URI, 
    null, 
    Contacts.Phones.PERSON_ID +" = ?", 
    new String[]{id}, null);
  int i=0;
  int pCount = pCur.getCount();
  String[] phoneNum = new String[pCount];
  String[] phoneType = new String[pCount];
  while (pCur.moveToNext()) {
   phoneNum[i] = pCur.getString(
                               pCur.getColumnIndex(Contacts.Phones.NUMBER));
   phoneType[i] = pCur.getString(
                               pCur.getColumnIndex(Contacts.Phones.TYPE));
   i++;
  } 
 }
Query the phones table and get a Cursor stored in pCur. Since the Android contacts database can store multiple phone numbers per contact we need to loop through the returned results. In addition to returning the phone number the query also returned the type of number (home, work, mobile, etc).
Email Addresses
Querying email addresses is similar to phone numbers. A special query must be performed to get email addresses from the database. Query the URI stored in Contacts.ContactMethods.CONTENT_EMAIL_URI to query the email addresses. 
 Cursor emailCur = cr.query( 
   Contacts.ContactMethods.CONTENT_EMAIL_URI, 
   null,
   Contacts.ContactMethods.PERSON_ID + " = ?", 
   new String[]{id}, null); 
 while (emailCur.moveToNext()) { 
     // This would allow you get several email addresses
 } 
 emailCur.close();
Simple query Contacts.ContactMethods.CONTENT_EMAIL_URI with a conditional limiting the results to numbers that match the ID of the contact record matches the value in the field Contacts.ContactMethods.PERSON_ID. As with phone numbers each contact can contain multiple email addresses so we need to loop through the Cursor records.

Android Contact API For 2.0

If you just read the begining of this article the first bit of this page is going to look familiar. This page is designed to act as a standalone guide to working with the contacts API in Android 2.0.

Querying The Android Contact Database
Retrieving Contact Details

Basic contact information stored in Contacts table with detailed information stored in individual tables for normalization. In Android 2.0 to query the base contact records the URI to query is stored in ContactsContract.Contacts.CONTENT_URI. 
package com.kais.TestContacts;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

public class TestContacts extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        if (cur.getCount() > 0) {
     while (cur.moveToNext()) {
         String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
  String name = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
   if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
       //Query phone here.  Covered next
          }
            }
  }
    }
}

This application starts off as any other Android application. First create a ContentResolver isntance in cr. Then use the ContentResolver instance to query the database and return a Cursor with the contacts list. The query is perofrmed against the URI stored in ContactsContract.Contacts.CONTENT_URI. Next check if the cursor contains records and if so loop through them. The record ID field is stored in the id variable. This will be used as a where parameter later. Also the display name field is stored in the string name.

Phone Numbers
Phone numbers are stored in their own table and need to be queried separately. To query the phone number table use the URI stored in the SDK variable ContactsContract.CommonDataKinds.Phone.CONTENT_URI. Use a WHERE conditional to get the phone numbers for the specified contact. 
            if (Integer.parseInt(cur.getString(
                   cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(
       ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
       null, 
       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
       new String[]{id}, null);
          while (pCur.moveToNext()) {
       // Do something with phones
          } 
          pCur.close();
      }

Perform a second query against the Android contacts SQLite database. The phone numbers are queried against the URI stored in ContactsContract.CommonDataKinds.Phone.CONTENT_URI. The contact ID is stored in the phone table as ContactsContract.CommonDataKinds.Phone.CONTACT_ID and the WHERE clause is used to limit the data returned.

Email Addresses
Querying email addresses is similar to phone numbers. A query must be performed to get email addresses from the database. Query the URI stored in ContactsContract.CommonDataKinds.Email.CONTENT_URI to query the email address table. 
 Cursor emailCur = cr.query( 
  ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
  null,
  ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
  new String[]{id}, null); 
 while (emailCur.moveToNext()) { 
     // This would allow you get several email addresses
            // if the email addresses were stored in an array
     String email = emailCur.getString(
                      emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
      String emailType = emailCur.getString(
                      emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 
  } 
  emailCur.close();

As with the phone query the field names for the email table are also stored under ContactsContract.CommonDataKinds. The email query is performed on the URI in ContactsContract.CommonDataKinds.Email.CONTENT_URI and the WHERE clause has to match the ContactsContract.CommonDataKinds.Email.CONTACT_ID field. Since multiple email addresses can be stored loop through the records returned in the Cursor.

No comments:

Post a Comment

Did this post help you? Do you have any questions? Drop your thoughts here...

}