Android 2.0 provides new Contact API, which is defined in android.provider.ContactsContract. After some try on contact api I found a better and easy solution for insertion and modification of contact.
Insert contact -
Intent addContactIntent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
addContactIntent.putExtra(ContactsContract.Intents.Insert.NAME,
"xyz");
addContactIntent.putExtra(ContactsContract.Intents.Insert.EMAIL,
"abc@gmail.com");
addContactIntent.putExtra(ContactsContract.Intents.Insert.PHONE,"012345678");startActivity(addContactIntent);
ACTION_INSERT will start .EditContact activity.
Edit contacts -
- If _ID of contact is known -
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, _ID));
startActivity(intent);
- If _ID of contact is not known -
i) Find out conatct _ID by phone number .
// CONTENT_FILTER_URI allow to search contact by phone number
Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(getPhone()));
// This query will return NAME and ID of conatct, associated with phone //number.
Cursor mcursor = getContentResolver().query(lookupUri,new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },null, null, null);
//Now retrive _ID from query result
long idPhone = 0;try {
if (mcursor != null) {
if (mcursor.moveToFirst()) {
idPhone = Long.valueOf(mcursor.getString(mcursor .getColumnIndex(PhoneLookup._ID)));
Log.d("", "Contact id::" + idPhone);
}
}
} finally {
mcursor.close();
}
ii) Then Edit contact
if (idPhone > 0) {Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, idPhone));
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "contact not in list",
Toast.LENGTH_SHORT).show();
}
You can also search _ID by partial name, for this instead of PhoneLookup.CONTENT_FILTER_URI use ContactsContract.Contacts.CONTENT_FILTER_URI
To work with contact, you have to define special permission in AndroidManifest.xml .
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

