I have code in a task trigger handler that looks to see if the whoid is a contact, and if so, set a pointer in the Task object to a field in the contact. So the trigger does this: - loop through the tasks passed to the trigger to make a set of contact ids when the whoid is a contact - do a query to lookup the contacts and put them in a map - loop again through the tasks and when the whoid is a contact, get the contact from the map and get the field.
However on occasion when the code gets the contact from the map, it appears that a null is returned. I don't understand how this can happen - does this make sense to anyone?
public void OnBeforeInsert(Task[] items) { SetContactInternalonActivity(items); } private void SetContactInternalonActivity(List<Task> newEntries){ Set<Id> contactIdSet = new Set<Id>(); for (Task t : newEntries) { if (TaskWhoIdIsAContact(t)) { contactIdSet.add(t.WhoId); } } if (contactIdSet.size() == 0) return; Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Id, Contact_Internal__c FROM Contact WHERE Id IN :contactIdSet]); for (Task t : newEntries) { if(TaskWhoIdIsAContact(t)) { ///// THE NEXT LINE OCCASIONALLY THROWS A System.NullPointerException EXCEPTION t.Contact_Internal__c = contacts.get(t.WhoId).Contact_Internal__c; } } } private boolean TaskWhoIdIsAContact(Task t) { return t.WhoId != null && (t.WhoId.getSobjectType() == Schema.Contact.SObjectType); }
with sharing? Perhaps the user read theWhoId, but not access the Contact record.