I've worked hard on the following code, but unfortunately, the entry is assigned to the wrong contact. I don't know why. Tested for hours days but can't find the mistake. Can you help me?
I would like to use the code in order to select a person from the contact list (using the contact picker) and then adding an event entry (date of birth) for this person to the contacts table.
Step 1:
I've already set the permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
Step 2:
The contact picker's ID is defined:
private static final int CONTACT_PICKER_ID = 123;
Step 3:
The contact picker is called:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_ID);
Step 4:
Another method listens for the contact picker's result and tries to add an event for the selected user:
@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 selectedPerson = data.getData();
String contactId = selectedPerson.getLastPathSegment();
// ADD A NEW EVENT FOR THE SELECTED CONTACT --- BEGIN
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
values.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.CommonDataKinds.Event.LABEL, "");
values.put(ContactsContract.CommonDataKinds.Event.START_DATE, "2010-01-28"); // hard-coded date of birth
Uri created = null;
try {
created = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
catch (Exception e) {
}
if (created == null) {
Toast.makeText(this.getApplicationContext(), "Failed inserting the event!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this.getApplicationContext(), "Successfully inserted the event!", Toast.LENGTH_SHORT).show();
}
// ADD A NEW EVENT FOR THE SELECTED CONTACT --- END
break;
}
}
}
The event is successfully inserted to the database and also shown in the Google contacts - but unfortunately it's assigned to the wrong contact. Why is this so? Is my contactId wrong that I get from the contact picker?