Friday, April 27, 2012

Android (Contacts): How to lookup and add contacts

This is how you can look-up for a specific contact in Android and do whatever you want if the contact is available or not.

The following code segment shows how the contact is programmatically added to contacts.

Check for an existing number in the Android contacts

Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                                                   Uri.encode(CommonVariables.merchantPhone));
String[] mPhoneNumberProjection = {
   ContactsContract.PhoneLookup._ID,
   ContactsContract.PhoneLookup.NUMBER,                  
   ContactsContract.PhoneLookup.DISPLAY_NAME
};

Cursor cur = context.getContentResolver().query(lookupUri,mPhoneNumberProjection, null, null, null);

if (cur != null && cur.moveToFirst()) {
   // The code to be executed if the phone number is available
}
else {
   // The code to be executed if the number is not available
}

Add a new number to the Android contacts

ArrayList op_list = new ArrayList();
op_list.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
 
op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,  ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, CommonVariables.merchantName)
.build());

op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)  .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, CommonVariables.merchantPhone)
.build());
 
op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
 .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
 .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
 .withValue(ContactsContract.CommonDataKinds.Email.DATA, getResources().getString(R.string.merchant_email))
    .build());

try {
  ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, op_list);
  Toast.makeText(AmountSet.this, getResources().getString(R.string.msg_contact_added), Toast.LENGTH_LONG).show();
} catch(Exception e){
  Toast.makeText(AmountSet.this, getResources().getString(R.string.msg_contact_error_adding), Toast.LENGTH_LONG).show();
  e.printStackTrace();
}