Question

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?

Was it helpful?

Solution

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());

OTHER TIPS

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();

here a code snipped i used

    newContactUri = null;
    try {
        ContentProviderResult[] res = globalContext.getContentResolver()
                .applyBatch(ContactsContract.AUTHORITY, ops);
        if (res != null && res[0] != null) {
            newContactUri = res[0].uri;
            /**
             * als Ergebnis erhaelt man eine URI, mit der man die raw
             * contact-id auslesen kann.
             */
            if (debug) {
                Log.d(TAG, "URI added contact:" + res[0].uri.toString()
                        + " l: " + res.length);
            }

            subQuery(newContactUri); // setzt contactRawID

        } else if (debug)
            Log.e( ....);

    } catch (Exception e) {
        if (debug)
            Log.d( .... );
    }

and this is the subroutine subQuery

/**
 * <pre>
 * nachdem ein user angelegt ist, wird damit 
 * die contactRawID gesetzt 
 * 
 * @param contactUri
 *            ... Ergebnis aus ContentProviderResult
 * @return void
 * </pre>
 */
public void subQuery(Uri contactUri) {
    if (debug)
        Log.i(TAG, "subQuery() ");

    contactRawID = -2;
    // Content Resolver
    String contactIdString = null;
    String displayName = null;
    ContentResolver contentResolver = globalContext.getContentResolver();
    String[] mainQueryProjection = { ContactsContract.RawContacts._ID,
            ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY };

    Cursor subQueryCursor = contentResolver.query(contactUri,
            mainQueryProjection, null, null, null);
    if (subQueryCursor != null) {
        if (debug)
            Log.d(TAG, "subQueryCursor != null ");
        while (subQueryCursor.moveToNext()) {
            contactIdString = subQueryCursor.getString(0);
            displayName = subQueryCursor.getString(1);
        }
        ;
        try {
            subQueryCursor.close();
        } catch (Exception e) {
            if (debug)
                Log.d(TAG, .... );
        }
        contactRawID = Integer.parseInt(contactIdString);
    }
    return;
}

many sorry for german comment text but i hope this helps a little bit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top