在Android中添加新联系人后如何获取联系人ID? [英] How to get contact id after add a new contact in android?

查看:122
本文介绍了在Android中添加新联系人后如何获取联系人ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下代码用于添加到手机的新联系人.

I use following code for new contacts added to phone.

private static void addContact(Account account, String name, String username,String phone,String email) {

    Log.i(TAG, "Adding contact: " + name);
    ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
    ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI);
    builder.withValue(RawContacts.ACCOUNT_NAME, account.name);
    builder.withValue(RawContacts.ACCOUNT_TYPE, account.type);
    builder.withValue(RawContacts.SYNC1, username);
    operationList.add(builder.build());

 //NAME adding area
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
    operationList.add(builder.build());

 // Phone Number adding area
    builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
    builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
    builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
    builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
    builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_WORK);
    operationList.add(builder.build());
    }

此代码可以很好地添加新联系人.

This code work fine for adding a new contact.

我想将服务器上的联系人更新为手机.因此,我需要联系人ID 以进行更新.

I want to update my contacts from server to phone. So I need contact id for updating purpose.

我可以从上述代码中获取联系人ID吗?.如果有人知道,请分享您的答案.

Can I get contact id from above code?. If anybody known share your answer.

如果有任何疑问或评论,也欢迎您.感谢您的回答.

If any questions or comments also welcome. Thanks for your answers.

推荐答案

尝试此代码,

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

Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
int contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash+1, length));

希望这段代码对您有所帮助.

I hope this code help you..

这篇关于在Android中添加新联系人后如何获取联系人ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆