How insert the contact info on the existing contac

2020-02-26 11:39发布

问题:

I have name, phone number and E-mail infomation of a contact. I just want to insert the additional email and phone for the existing contact. My questions are

  1. How to find the contact is already existing or not?
  2. How to insert the values on the additional or secondary address option?

Thanks in Advance.

回答1:

In the official document has new contancts api.

http://developer.android.com/reference/android/provider/ContactsContract.Data.html

First, look up raw contacts id with your criteria, such as name:

final String name = "reader";
// find "reader"'s contact 
String select = String.format("%s=? AND %s='%s'", 
        Data.DISPLAY_NAME, Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
String[] project = new String[] { Data.RAW_CONTACT_ID };
Cursor c = getContentResolver().query(
        Data.CONTENT_URI, project, select, new String[] { name }, null);

long rawContactId = -1;
if(c.moveToFirst()){
    rawContactId = c.getLong(c.getColumnIndex(Data.RAW_CONTACT_ID));
}
c.close();

Second, use rawContactId to add an entry to contacts:

ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, "1-800-GOOG-411");
values.put(Phone.TYPE, Phone.TYPE_CUSTOM);
values.put(Phone.LABEL, "free directory assistance");
Uri dataUri = getContentResolver().insert(Data.CONTENT_URI, values);

PS. don't forget the permissions:

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>