0

Get the following error on occasion and trying to track it down this is pre-existing custom code on a site i work on. Let me know if you see an obvious cause.

Developer script exception from : eventTrigger : eventTrigger: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object ()

Apex script unhandled trigger exception by user/organization:

eventTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Class.EventTriggerHandler.createTask: line 121, column 1

Class.EventTriggerHandler.handleAfterInsert: line 63, column 1

Trigger.eventTrigger: line 6, column 1

Event Trigger in question

trigger eventTrigger on Event (after insert, after update) {

    if((trigger.isafter)&&(trigger.isinsert))
    {
        EventTriggerHandler ev = new EventTriggerHandler();
        ev.handleAfterInsert(trigger.new);
    }
    
    if((trigger.isafter)&&(trigger.isupdate))
    {
        EventTriggerHandler ev = new EventTriggerHandler();
        ev.handleBeforeUpdate(trigger.oldmap,trigger.newmap);
    }
}

The handler is below

public class EventTriggerHandler{
    
    public map<id,id> ownerId = new map<id,id>();
    public list<task> taskList = new list<task>();
    public list<id> Owners = new list<id>();
    public list<id> contactIds = new list<id>();
    
    public void handleBeforeUpdate(map<id,event> eventListBefore, map<id,event> eventListAfter){
     
        map<id,user> userList = new map<id,user>([select name,id,email from user]);
        for(event ev : eventListAfter.values())
        {
           if(ev.WhatId != null)
           {
            if((ev.Event_Type__c == 'New Job')&&(ev.Event_Type__c != eventListBefore.get(ev.id).Event_Type__c))
            {
               // if(string.valueof(ev.whatId).startsWith('006'))
                {
                    ownerId.put(ev.WhatId,ev.id);
                    Owners.add(ev.OwnerId);
                    contactIds.add(ev.whoId);
                    
                }
            }
           }
        }
        
        
        if(ownerId.keyset().size()>0) 
        {
            createTask(eventListAfter.values(),contactIds,userList,ownerId);
        
            insert taskList;
        }
    
    }
    
    public void handleAfterInsert(list<event> newEventList)
    {
       
        map<id,user> userList = new map<id,user>([select name,id,email from user]);
        for(event ev : newEventList)
        {
            if(ev.whatId != null)
            {
               // if((string.valueof(ev.whatId).startsWith('006'))&&(ev.Event_Type__c == 'New Job')&&(ev.whatId != null))
                if((ev.Event_Type__c == 'New Job')&&(ev.whatId != null))   
                {
                    ownerId.put(ev.WhatId,ev.id);
                    Owners.add(ev.OwnerId);
                    contactIds.add(ev.whoId);
                                  
                }
            }
        }
        
        
        
        system.debug('ownerId --> '+ownerId);
        if(ownerId.keyset().size()>0)
        {
         
          createTask(newEventList,contactIds,userList,ownerId);
          system.debug('task list -->' + taskList);
          insert taskList;
        }
        
    }
    
    //Create activity history for sent mails
    private void createTask(list<event> eventList,list<id> ContacIds,map<id,user> userList,map<id,id> OwnerId)
    {
        map<id,contact> con = new map<id,contact>([select id,name from contact where id IN :ContacIds]);
        map<id,user> users = new map<id,user>([select id, name,Email from user]);
        //map<id,opportunity> opp = new map<id,opportunity>([select id, name,OwnerId, Owner.name, Owner.Email from opportunity where id IN :OwnerId.keyset()]);
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        List<id> accountId = new list<id>();
        Id IdValue;
        //Test code -- start
        for(id ownerValue : OwnerId.keyset())
        {
            IdValue =  ownerValue;
        }
        
        String sObjName = IdValue.getSObjectType().getDescribe().getName();
        set<id> sobjectIds = OwnerId.keyset();
        string query = 'select id, name,OwnerId,Owner.name,Owner.email from '+ sObjName +' where Id IN :sobjectIds';
        list<SObject> objectData= new list<SObject>();
        objectData = database.query(query);
        system.debug('data value --> '+objectData);
        map<id,SObject> SObjectMap = new map<id,SObject>();
        for(SObject so : objectData)
        {
            SObjectMap.put(so.id,so);
        }
        
        system.debug('map value -->'+SObjectMap);
        //Test code -- End
        for(event ev: eventList)
        {
            accountId.add(ev.Account__c);
        }
        
        map<id,account> accountMap = new map<id,account>([select id, name from account where id IN :accountId]);
         
        for(event ev: eventList)
        {
            string startDateValue='';
            string endDateValue='';
            if(ev.IsAllDayEvent)
            {
                startDateValue = string.valueof(ev.StartDateTime.adddays(1).date().format());
                endDateValue = string.valueof(ev.EndDateTime.adddays(1).date().format());
            }
            else
            {
                startDateValue = string.valueof(ev.StartDateTime.format());
                endDateValue = string.valueof(ev.EndDateTime.format());
            }
            
            string subject1 = 'Email:'+string.valueof(userList.get(ev.OwnerId).name)+' @ '+string.valueof(accountMap.get(ev.Account__c).name)+' from '+startDateValue+' - '+endDateValue;
            string comment1 = 'To: '+string.valueof(userList.get(ev.OwnerId).name)+','+string.valueof(userList.get(Id.valueof(string.valueof(SObjectMap.get(ev.WhatId).get('OwnerId')))).name);
            comment1 = comment1+'\n'+'CC: '+string.valueof(userList.get(ev.CreatedById).name);
            comment1 = comment1+'\n'+'Subject: '+string.valueof(userList.get(ev.OwnerId).name)+' @ '+string.valueof(accountMap.get(ev.Account__c).name)+' from '+startDateValue +' - '+endDateValue+'\n\n';
            comment1 = comment1+'Body: '+'\n'+'A new job has been scheduled: \n\n';
            comment1 = comment1+string.valueof(URL.getSalesforceBaseUrl().toExternalForm())+'/'+string.valueof(ev.id)+'\n\n';
            comment1 = comment1+'Consultant: '+string.valueof(userList.get(ev.OwnerId).name)+'\n'+'Account: '+string.valueof(accountMap.get(ev.Account__c).name)+'\n';
            comment1 = comment1+'Main Contact: '+string.valueof(con.get(ev.WhoId).name)+'\n';
            comment1 = comment1+'Start Date: '+startDateValue+'\n End Date: '+endDateValue+'\n';
            comment1 = comment1+'Description: '+string.valueof(ev.Description)+'\n\n'+'Related To Ref: '+string.valueof(SObjectMap.get(ev.WhatId).get('name'));
            task ta = new task(Description=comment1,Type = 'Email',WhatId=ev.whatId,Status='Completed',ActivityDate = system.today(),Subject=subject1);
            taskList.add(ta);   
            
            // Create and send mails
           
            
            string subjectValue = string.valueof(userList.get(ev.OwnerId).name)+' @ '+string.valueof(accountMap.get(ev.Account__c).name)+' from '+startDateValue+' - '+endDateValue;
            string bodyValue = 'A new job has been scheduled: <br/><br/>';
            bodyValue = bodyValue+string.valueof(URL.getSalesforceBaseUrl().toExternalForm())+'/'+string.valueof(ev.id)+'<br/><br/><br/>';
            bodyValue = bodyValue+'Consultant: '+string.valueof(userList.get(ev.OwnerId).name)+'<br/>'+'Account: '+string.valueof(accountMap.get(ev.Account__c).name)+'<br/>';
            bodyValue = bodyValue+'Main Contact: '+string.valueof(con.get(ev.WhoId).name)+'<br/>';
            bodyValue = bodyValue+'Start Date: '+startDateValue+'<br/> End Date: '+endDateValue+'<br/>';
            bodyValue = bodyValue+'Description: '+string.valueof(ev.Description)+'<br/><br/><br/>';
            bodyValue = bodyValue+'Related To Ref: '+'<a href=\"'+string.valueof(URL.getSalesforceBaseUrl().toExternalForm())+'/'+string.valueof(ev.WhatId)+'\">'+string.valueof(SObjectMap.get(ev.WhatId).get('name'))+'</a>';
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.saveAsActivity = false;
            mail.setSubject(subjectValue);
           // mail.setTargetObjectId(ev.OwnerId);
            list<string> owners = new list<string>();
            owners.add(users.get(ev.OwnerId).Email);
            //if(string.valueof(ev.whatId).startswith('006'))
            {
                owners.add(userList.get(Id.valueof(string.valueof(SObjectMap.get(ev.WhatId).get('OwnerId')))).email);
            }
            
            
            mail.setToAddresses(owners);
            mail.setHtmlBody(bodyValue);
            string creatorEmail = string.valueof(users.get(ev.CreatedById).Email);
            
            mail.setCCAddresses(new string[]{creatorEmail});
            mails.add(mail);
            
        }
        
        if(mails.size()>0)
        {
            Messaging.sendEmail(mails);
        }
        
        
        
    }
   
    
}
2
  • Have you tried to remove system debugs? Sometimes System.debugs can cause null-pointer errors.
    – thinker
    Commented Mar 9, 2021 at 20:27
  • what have you done or debugged on your own? It gives a line # in the error, what exact line is it? Commented Mar 9, 2021 at 20:29

1 Answer 1

0

It looks like:

        string subject1 = 'Email:'+string.valueof(userList.get(ev.OwnerId).name)+' @ '+string.valueof(accountMap.get(ev.Account__c).name)+' from '+startDateValue+' - '+endDateValue;

Is the problem line. Most likely it's a missing value in one of the maps.

I would suggest using the new Safe Navigation Operator (?.) to avoid this error:

string subject1 = 'Email:'+
  userList.get(ev.OwnerId)?.name+
  ' @ '+
  accountMap.get(ev.Account__c)?.name+
  ' from '+
  startDateValue+
  ' - '+
  endDateValue;

This is the easy fix. A more appropriate fix will require checking the maps to make sure there are no null values. You may also need to check the map to see if there's data that should have been queried but wasn't for some reason.

P.S. I only demonstrated one line, but all of this code needs to be fixed. It might be easier to refactor the variables into their own section to avoid code duplication:

String ownerName = UserList.get(ev.OwnerId)?.Name;
String accountName = accountMap.get(ev.Account__c)?.Name;

String subject1 = 'Email:'+ownerName+' @ '+accountName+' from '+startDateValue+' - '+endDateValue;
1
  • Thanks that appears to have resolved that issue. Commented Mar 16, 2021 at 21:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .