I am hoping that someone can teach me a little about how to work through this null pointer error. The class is called from a trigger handler on After Update because I need access to all ID fields. The error is getting thrown at the final for loop where I am trying to assign the values of the map to the field unique_emails_sent__c. Add the appropriate records to a list and then update the list. The default value of the field is set to 0. Any help or teaching moments would be appreciated.
public static void uniqueRelationshipOwnerEmails(List<relationship_owner__c> roList){
//count the unique emails that have been sent by a relationship owner
// add all contacts associated with relationship owner to map.
Map<id, Contact> contactMap = new Map<Id, Contact>([SELECT Id,
New_Relationship_Owner1__c
FROM Contact
WHERE New_Relationship_owner1__c IN : roList]);
system.debug('Contacts found = ' + contactMap.size());
//put tasks where whoId is in the contact map into a new map
List<Task> taskList = [SELECT Id, WhoId,Subject
FROM Task
WHERE WhoId IN :contactMap.keySet()
AND Subject LIKE '%Pardot List Email%'];
system.debug('Tasks Found and added to map = ' + taskList.size());
//use set to dedupe the list
Map<Id, Set<String>> subjectLineMap = new Map<Id, Set<String>>();
for(task t : taskList){
Id ownerId = contactMap.get(t.WhoId).New_Relationship_Owner1__c;
if(!subjectLineMap.containsKey(ownerId)){
subjectLineMap.put(ownerId, new Set<String>());
}
}
system.debug('Map size =' + subjectLineMap.size());
system.debug('map values =' + subjectLineMap.values());
system.debug('map keys =' + subjectLineMap.Keyset());
List<relationship_owner__c> updatedRelationshipOwners = new List<relationship_owner__c>();
for(relationship_owner__c r : roList){
r.Unique_Emails_Sent__c = subjectLineMap.get(r.Id).size();
updatedRelationshipOwners.add(r);
}
if(updatedRelationshipOwners != null){
update(updatedRelationshipOwners);
}
}
}
I edited the for loop to try and check for the null but I am still getting the error.
for(relationship_owner__c r : roList){
if(!subjectLineMap.containsKey(r.id)){
r.Unique_Emails_Sent__c = subjectLineMap.get(r.Id).size();
updatedRelationshipOwners.add(r);
}
Best Answer
The reason your'e getting a Null pointer exception was you are trying to get a value before checking if ever existed or not. To check that you need to check if the value existed in the map keyset.
Like i mentioned in the comments your'e checking for nagation(!) which translates to If it doesn't contain key. you should remove the negation. Because we want to get the value only if the key exists