Android How to - Save data to Contact book








Question

We would like to know how to save data to Contact book.

Answer

//from   w  w  w .java 2  s . co m
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;

class AddressBookUtil {
  private Context context;

  public AddressBookUtil(Context context) {
    this.context = context;
  }

  public void save(String name, String phone1, String phone2) {
    ContentValues values = new ContentValues();
    Uri rawContactUri = context.getContentResolver().insert(
        RawContacts.CONTENT_URI, values);
    long rawContactId = ContentUris.parseId(rawContactUri);
    if (name != "") {
      values.clear();
      values.put(Data.RAW_CONTACT_ID, rawContactId);
      values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
      values.put(StructuredName.GIVEN_NAME, name);
      context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
          values);
    }
    if (phone1 != "") {
      values.clear();
      values.put(Data.RAW_CONTACT_ID, rawContactId);
      values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
      values.put(Phone.NUMBER, phone1);
      values.put(Phone.TYPE, Phone.TYPE_MOBILE);
      context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
          values);
    }
    if (phone2 != "") {
      values.clear();
      values.put(Data.RAW_CONTACT_ID, rawContactId);
      values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
      values.put(Phone.NUMBER, phone1);
      values.put(Phone.TYPE, Phone.TYPE_OTHER);
      context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI,
          values);
    }
  }
}