Reputation: 501
I am saving a contact by this code
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);
After saving the contact, I need to get the _ID field so that I can fetch that contact from the contact book for editing. How can I get the id after saving?
Thanks in advance
Upvotes: 5
Views: 1093
Reputation: 6156
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Uri myContactUri = res[0].uri;
int contactID = Integer.parseInt(myContactUri.getLastPathSegment());
Upvotes: 3
Reputation: 2661
Here you go. Get the contact id for the number( ´phnumber` ) from the contacts
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();
}
Upvotes: 0