Monday, 23 April 2012

Android contacts: CONTACT_ID vs RAW_CONTACT_ID - A brief study

Almost everybody who works with Android contacts asks the same question: What is CONTACT_ID, what is RAW_CONTACT_ID and what is the difference between them? To unveil this mistery for myself, I did some debugging on Android and got a good understanding how it works. Because I couldn't find a comprehensive explanation of this subject anywhere, I decided to share my findings with anybody who would be interested.

In summary, RAW_CONTACT_ID refers to every individual contact you create on Android; this is referred to as raw contact. Some of the raw contacts are automatically grouped together. CONTACT_ID refers to such a group. There is a one-to-many relationship between CONTACT_ID and RAW_CONTACT_ID.

Let's consider some examples and start by creating contact entries.


CREATE A CONTACT

Suppose that we create the following contacts, in the specified order.

1. Katherine Solomon - Home: 01-234-5678

2. Katherine Solomon - Work: katherine.solomon@lostsymbol.com

Android groups these two contacts together and shows them as a single entry in the contacts list. The values of CONTACT_ID and  RAW_CONTACT_ID are shown below. We assume that we start from a clean phone; hense the numbers start from 1 (Hint: You can always start from a clean emulator if you wish. Just create a new Android Virtual Device).

Katherine Solomon
1.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:1
  StructuredName.DISPLAY_NAME:Katherine Solomon
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Solomon
  Phone.NUMBER:01-234-5678
  Phone.TYPE:TYPE_HOME

2.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:2
  StructuredName.DISPLAY_NAME:Katherine Solomon
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Solomon
  Email.DATA:katherine.solomon@lostsymbol.com
  Email.TYPE:TYPE_WORK

The two "Katherine Solomons" we just created are automatically grouped together and are assigned the same CONTACT_ID. However, each entry has its unique RAW_CONTACT_ID. When you open Android contacts, you'll see one entry for Katherine Solomon, showing both the phone number and the e-mail address. This is the CONTACT. However, when you edit this contact, then you'll see two entries for Katherine Solomon; one showing the phone number and the other showing the e-mail address. These are the RAW_CONTACTS.

Next we add another contact entry:

3. Robert Langdon - Home: 01-876-5432,  Work:  robert.langdon@lostsymbol.com
(This time we specify both a phone number and an e-mail address when creating the entry.)

Then the related entries for this contact are as follows:

Robert Langdon
  Data.CONTACT_ID:3
  Data.RAW_CONTACT_ID:3
  StructuredName.DISPLAY_NAME:Robert Langdon
  StructuredName.GIVEN_NAME:Robert
  StructuredName.FAMILY_NAME:Langdon
  Phone.NUMBER:01-876-5432
  Phone.TYPE:TYPE_HOME
  Email.DATA:robert.langdon@lostsymbol.com
  Email.TYPE:TYPE_WORK

Because the new contact has a different name, it is not grouped with any of the existing ones and gets its own CONTACT_ID. Android contacts show two entries now, one for Katherine Solomon and one for Robert Langdon.

It's worth to note that there is a 1-to-1 relationship between the CONTACT_ID and the DISPLAY_NAME.

The next question is, what happens when you change the name of a contact. How does this affect, or does it affect the existing groupings?


EDIT THE NAME OF AN EXISTING CONTACT

Suppose that Katherine Solomon gets married and changes her family name to Langdon. Suppose also that we update the family name only of the entry RAW_CONTACT_ID:1 but we do not update the family name of the entry RAW_CONTACT_ID:2.

Then Android contacts still show two entries in the contacts list:

Katherine Solomon
Robert Langdon

Then the related entries for Katherine Solomon are as as displayed below. The arrow (<---) shows the only value which has changed.

Katherine Solomon
1.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:1
  StructuredName.DISPLAY_NAME:Katherine Solomon
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Langdon  <---
  Phone.NUMBER:01-234-5678
  Phone.TYPE:TYPE_HOME

2.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:2
  StructuredName.DISPLAY_NAME:Katherine Solomon
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Solomon
  Email.DATA:katherine.solomon@lostsymbol.com
  Email.TYPE:TYPE_WORK

Please note that the display name of both entries remain the same and both entries are still grouped together, even though we changed the FAMILY_NAME of one of them.

If we change the FAMILY_NAME of the entry with RAW_CONTACT_ID:2 also, then the display name of the group as well is changed and the following entry appears in Android contacts:

Katherine  Langdon
1.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:1
  StructuredName.DISPLAY_NAME:Katherine Langdon  <---
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Langdon
  Phone.NUMBER:01-234-5678
  Phone.TYPE:TYPE_HOME

2.Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:2
  StructuredName.DISPLAY_NAME:Katherine Langdon  <---
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Langdon  <---
  Email.DATA:katherine.solomon@lostsymbol.com
  Email.TYPE:TYPE_WORK

In my opinion, this behavior is very handy and it makes the life of a software developer very easy when dealing with Android contacts.

But, what is the behavior when we delete contacts?


DELETE A CONTACT

Android contacts allow deleting a CONTACT and not individual RAW_CONTACT. If we delete "Katherine  Langdon" then both raw contacts RAW_CONTACT_ID:1 and RAW_CONTACT_ID:2 will be deleted.

Programmatically, it's possible to do more of course.


PROGRAMMATICALLY INSERT A CONTACT INTO A DESIRED GROUP

Suppose that we have the original "Katherine Solomon" contacts we created and we have not deleted any contact entry. Next, we programmatically insert the following contact: 

// For brevity the ContactsContract and 
// ContactsContract.CommonDataKinds prefixes are ignored.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
    .withValue(RawContacts.ACCOUNT_TYPE, null)
    .withValue(RawContacts.ACCOUNT_NAME, null)
    .build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
    .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
    .withValue(StructuredName.DISPLAY_NAME, "Lost Symbol Characters")
    .withValue(StructuredName.GIVEN_NAME, "Katherine")
    .withValue(StructuredName.FAMILY_NAME, "Solomon")
    .build());  
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
    .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
    .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
    .withValue(Phone.NUMBER, "09876543")
    .withValue(Phone.TYPE, Phone.TYPE_MOBILE)                
    .build());
// For brevity, the try-catch statement is ignored.
// Normally it's needed.
getContentResolver().applyBatch(AUTHORITY, ops);

In this operation we specifically assigned a DISPLAY_NAME value to the new contract. Even though the GIVEN_NAME and FAMILY_NAME of the new contact is exactly the same with the contacts  RAW_CONTACT_ID:1 and RAW_CONTACT_ID:2, the new contact gets a new CONTACT_ID and appears under a new group. The new entry in Android contacts is as follows:

Lost Symbol Characters
  Data.CONTACT_ID:4
  Data.RAW_CONTACT_ID:4
  StructuredName.DISPLAY_NAME:Lost Symbol Characters
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Solomon
  Phone.NUMBER:09876543
  Phone.TYPE:TYPE_MOBILE


PROGRAMMATICALLY DELETE A RAW_CONTRACT

Programmatically it's possible to delete raw contacts. Suppose that we programmaticall delete  RAW_CONTACT_ID:1 using the code below.

// For brevity the ContactsContract and 
// ContactsContract.CommonDataKinds prefixes are ignored.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
    .withSelection(RawContacts._ID + " = ?", new String[]{"1"})
    .build());
// For brevity, the try-catch statement is ignored.
// Normally it's needed.
getContentResolver().applyBatch(AUTHORITY, ops);

After this deletion the entries for "Katherine Solomon" are as follows:

Katherine Solomon
  Data.CONTACT_ID:1
  Data.RAW_CONTACT_ID:2
  StructuredName.DISPLAY_NAME:Katherine Solomon
  StructuredName.GIVEN_NAME:Katherine
  StructuredName.FAMILY_NAME:Solomon
  Email.DATA:katherine.solomon@lostsymbol.com
  Email.TYPE:TYPE_WORK


This has been my brief investigation of Android ContactsContract. I also tried to update the DISPLAY_NAME of a raw contract but the behavior I observed seems to be buggy. (The corresponding bug entry is: http://code.google.com/p/android/issues/detail?id=16188&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars) In general my opinion is that, the Android folks did a good job in designing ContactsContract. I find it very convenient to work with it.

Android Recipes and Snippets

I've put together a small collection of Android recipes. For each of these recipes, this is an instance of Context (more specifically, Activity or Service) unless otherwise noted. Enjoy :)

Intents
One of the coolest things about Android is Intents. The two most common uses of Intents are starting an Activity (open an email, contact, etc.) and starting an Activity for a result (scan a barcode, take a picture to attach to an email, etc.). Intents are specified primarily using action strings and URIs. Here are some things you can do with the android.intent.action.VIEWaction and startActivity().
Intent intent = new Intent(Intent.ACTION_VIEW);
// Choose a value for uri from the following.
// Search Google Maps: geo:0,0?q=query
// Show contacts: content://contacts/people
// Show a URL: http://www.google.com
intent.setData(Uri.parse(uri));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Other useful action/URI pairs include:
  • Intent.ACTION_DIALtel://8675309
  • Intent.ACTION_CALLtel://8675309
More interesting things are available when you use startActivityForResult(). For example, to scan a barcode:
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
Then, add onActivityResult to your activity.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    Bundle extras = data.getExtras();
    String result = extras.getStringExtra("SCAN_RESULT");
    // ...
  }
}
Taking a picture is done like so:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
// ...

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (resultCode == Activity.RESULT_OK && requestCode == 0) {
    String result = data.toURI();
    // ...
  }
}
Check out the OpenIntents registry for more information.

Wifi

The WifiManager can be used to enable and disable wifi. Where enabled is a boolean, it's as easy as:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);
Notifications
Text notifications (called Toast) which appear briefly above all activities are also easy:
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
You can increase the time the notification is displayed by using Toast.LENGTH_LONG instead.

Alert and Input Dialogs
Sometimes it's useful to prompt the user for input. An easy way to do that without creating a new layout is to useAlertDialog.Builder.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(title);
alert.setMessage(message);

// You can set an EditText view to get user input besides
// which button was pressed.
final EditText input = new EditText(this);
alert.setView(input);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
  String value = input.getText();
  // Do something with value!
  }
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int whichButton) {
    // Canceled.
  }
});

alert.show();
Location
Use the LocationManager to start up the GPS and listen for location updates.
LocationManager locator = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocationListener = new LocationListener() {
  public void onLocationChanged(Location location) {
    if (location != null) {
      location.getAltitude();
      location.getLatitude();
      location.getLongitude();
      location.getTime();
      location.getAccuracy();
      location.getSpeed();
      location.getProvider();
    }
  }

  public void onProviderDisabled(String provider) {
    // ...
  }

  public void onProviderEnabled(String provider) {
    // ...
  }

  public void onStatusChanged(String provider, int status, Bundle extras) {
    // ...
  }
};

// You need to specify a Criteria for picking the location data source.
// The criteria can include power requirements.
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);  // Faster, no GPS fix.
criteria.setAccuracy(Criteria.ACCURACY_FINE);  // More accurate, GPS fix.
// You can specify the time and distance between location updates.
// Both are useful for reducing power requirements.
mLocationManager.requestLocationUpdates(mLocationManager.getBestProvider(criteria, true),
    MIN_LOCATION_UPDATE_TIME, MIN_LOCATION_UPDATE_DISTANCE, mLocationListener,
    getMainLooper());
You can also get the phone's last known location using the LocationManager. This is faster than setting up aLocationListener and waiting for a fix.
// Start with fine location.
Location l = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (l == null) {
  // Fall back to coarse location.
  l = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
SMS
Sending a text is done with the SmsManager.
SmsManager m = SmsManager.getDefault();
String destination = "8675309";
String text = "Hello, Jenny!";
m.sendTextMessage(destination, null, text, null, null);
Vibrate
You can vibrate the phone for a specified duration like so:
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE).vibrate(milliseconds);
Sensors
Accessing sensor data is done using the SensorManager.
SensorManager mSensorManager = (SensorManager) getSystemService(Activity.SENSOR_SERVICE);
private final SensorListener mSensorListener = new SensorListener() {
  public void onAccuracyChanged(int sensor, int accuracy) {
    // ...
  }

  public void onSensorChanged(int sensor, float[] values) {
    switch (sensor) {
      case SensorManager.SENSOR_ORIENTATION:
        float azimuth = values[0];
        float pitch = values[1];
        float roll = values[2];
        break;
      case SensorManager.SENSOR_ACCELEROMETER:
        float xforce = values[0];
        float yforce = values[1];
        float zforce = values[2];
        break;
      case SensorManager.SENSOR_MAGNETIC_FIELD:
        float xmag = values[0];
        float ymag = values[1];
        float zmag = values[2];
        break;
    }
  }
};

// Start listening to all sensors.
mSensorManager.registerListener(mSensorListener, mSensorManager.getSensors());
// ...
// Stop listening to sensors.
mSensorManager.unregisterListener(mSensorListener);
Silence Ringer
You can use the AudioManager to enable and disable silent mode.
mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
// or...
mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Useful LinksThat's it from me for now. But, here are some useful sources of more information: