Question

In an activity of my Android application, I would like to open the content picker. And when the user selects one of those contacts, there should be a new entry (an event with type "other") that is inserted into the table ContactsContract.CommonDataKinds.Event.

Starting the contact picker intent is easy. But then one must get some data for the selected contact and create a new entry in the event table. This is the code I have so far, unfortunately it doesn't work:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {  
        switch (requestCode) {  
            case CONTACT_PICKER_ID:  
            Uri contactData = data.getData();
            //String contactID = contactData.getLastPathSegment();
            // ADD A NEW BIRTHDAY FOR THE SELECTED CONTACT START
            ContentValues values = new ContentValues();
            values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_OTHER);
            values.put(ContactsContract.CommonDataKinds.Event.CONTACT_ID, 250);
            values.put(ContactsContract.CommonDataKinds.Event.START_DATE, "2012-12-12");
            Uri dataUri = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
            // ADD A NEW BIRTHDAY FOR THE SELECTED CONTACT END
            break;
        }
    }
}

This code requires the permission "WRITE_CONTACTS".

The contact ID "250" is hard-coded. Of course, it should be retrieved from the intent data that is sent along with the contact picker's result.

The code above terminates with a NullPointerException. Why is this so? And how do I get the contact's id from the intent so that I can use it for inserting the new row?

Edit: Additionally, the line ...

getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);

... throws an exception. What's wrong there?

Was it helpful?

Solution

Here's how to do it, assuming this is how you called the contact picker:

int CONTACT_PICKER_ID = 1001; //some arbitrary number that you choose
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivity(intent, CONTACT_PICKER_ID);

The data.getData() call returns a lookup key that you have to query the contacts DB for to find the contact's ID.

if (resultCode == RESULT_OK) {  
    switch (requestCode) {  
        case CONTACT_PICKER_ID:  
            Cursor cursor =  managedQuery(data.getData(), null, null, null, null);
            cursor.moveToFirst();
            //get the contact's ID
            contactId = Cursor.getLong(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

...

The contactId contains the ID you want.

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