保存android联系后获取联系人ID

时间:2013-09-16 12:52:22

标签: android contact

我正在通过此代码保存联系人

ArrayList<ContentProviderOperation> ops =
          new ArrayList<ContentProviderOperation>();
 ...
 int rawContactInsertIndex = ops.size();
 ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
          .withValue(RawContacts.ACCOUNT_TYPE, accountType)
          .withValue(RawContacts.ACCOUNT_NAME, accountName)
          .build());

 ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
          .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
          .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
          .withValue(StructuredName.GIVEN_NAME, linkname1)
          .withValue(StructuredName.FAMILY_NAME, linkname2)
          .build());

 getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

保存联系人后,我需要获取_ID字段,以便我可以从联系簿中获取该联系人进行编辑。保存后如何获取ID?

提前致谢

2 个答案:

答案 0 :(得分:3)

ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

Uri myContactUri = res[0].uri;
int contactID = Integer.parseInt(myContactUri.getLastPathSegment());

答案 1 :(得分:0)

你走了。从联系人

获取号码('phnumber`)的联系人ID
String[] projection = new String[]{Contacts._ID};
Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(phnumber));
Cursor c = getContentResolver().query(contactUri, projection,
  null, null, null);
if (c.moveToFirst()) {
long contactId=c.getColumnIndex(Contacts._ID);


c.close();

}