Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: get contact id after insert

I need to store the contact id value after create a new contact, in order to be able to reference it in other moment. For example, I create a new contact, and after that I want to delete it from its contact id, so I need to retrieve the contact id value after create a new contact. This is how I create new contacts:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, tipoCuenta).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, cuenta).build());

//Insert some data here....

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

//Here, I want to retrieve contact id

How can I do that?

like image 368
user3057179 Avatar asked May 07 '14 15:05

user3057179


2 Answers

The ContentResolver.applyBatch() method returns an array of ContentProviderResult objects, one for each operation. Each of these has the uri of the inserted contact (in the format content://com.android.contacts/raw_contacts/<contact_id>).

So to get the contact's id you just have to parse this uri, i.e.

ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
int contactId = Integer.parseInt(results[0].uri.getLastPathSegment());
like image 171
matiash Avatar answered Oct 22 '22 00:10

matiash


Improving on matiash answer:

The ContentResolver.applyBatch() method returns an array of ContentProviderResult objects, one for each operation. If your first operation adds RawContact then first element of result array will contain uri to added RawContact (in the format content://com.android.contacts/raw_contacts/[raw_contact_id]).

If you are interested in raw_contact_id then following is enough:

    final ContentProviderResult[] results = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    long rawContactId = ContentUris.parseId(results[0].uri);

But raw_contact_id on some devices might be different than contact_id - In order to get contact_id you have to do following:

    final ContentProviderResult[] results = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
    final String[] projection = new String[] { ContactsContract.RawContacts.CONTACT_ID };
    final Cursor cursor = contentResolver.query(results[0].uri, projection, null, null, null);
    cursor.moveToNext();
    long contactId = cursor.getLong(0);
    cursor.close();
like image 24
krulik Avatar answered Oct 22 '22 02:10

krulik