function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Hanna BergsmaHanna Bergsma 

System.NullPointerException: Attempt to de-reference a null object Trigger and Handler

I am our orgs admin and I am trying to fix code set up in 2016 by a previous employee. I know very little about apex but I understand my SOQL query is pulling 0 records and I need to solve for that. I am recieving the following emails. Thank you in advance, Ive been working on this for days! 
"OrderTrigger: execution of AfterInsert

caused by: System.NullPointerException: Attempt to de-reference a null object
Class.OrderTriggerHandler.insertOrder: line 21, column 1
Trigger.OrderTrigger: line 4, column 1"


My trigger is very short, i have bolded line 4 per the email error:

trigger OrderTrigger on Order (after insert) {

    if(Trigger.isInsert){
       OrderTriggerHandler.insertOrder(Trigger.new);  
     }

}

My handler is as follows, i have bolded line 21 per error email:
public with sharing class OrderTriggerHandler{

    public Static void insertOrder(List<Order> objOrder)
    {
        
         Set<Id> objAcc = new Set<Id>();
         for(Order objOr : objOrder){
             objAcc.add(objOr.AccountId);
         }
         
         
         List<Contact> objCon = [select id,name,Email,AccountId,Account.Parent.ParentId, Account.Parent.Parent.Name from Contact where AccountId IN : objAcc];
         String partnerName;
         Id wideEmailAddressId;
         if(objCon.size() > 0){
             List<String> objMail = new List<String>();
             Set<String> objSetAcc = new Set<String>();
             for(Contact objContact : objCon){
                 objMail.add(objContact.Email);
                 partnerName = objContact.Account.Parent.Parent.Name;
                 String accId = String.valueOf(objContact.Account.Parent.ParentId).substring(0, 15);
                 objSetAcc.add('New Order Notification'+accId);
             }
             
        for(OrgWideEmailAddress owa : [select id, Address, DisplayName from OrgWideEmailAddress where DisplayName='EvoLaw, LLC']) {
             if(owa.Address.contains('CSR')) wideEmailAddressId = owa.id; 
        } 
        System.debug('&&&&&&&objSetAcc&&&&&& '+objSetAcc);
        
        
       List<EmailTemplate> templateId = [Select id,Subject, HtmlValue, Body from EmailTemplate where name IN : objSetAcc];
       System.debug('&&&&&&&templateId&&&&&& '+templateId);
       if(templateId.size() > 0){ 
       
            System.debug('&&&&&&&templateId &&&&& '+templateId[0]); 
           String [] emailsAsArray = new String [objMail.size()];
            Integer i = 0;
            for (String singleCCEmail: objMail) {
                emailsAsArray[i++] = singleCCEmail;
            }  
             
           
           String subject =templateId[0].Subject ;
           String htmlBody = templateId[0].HtmlValue ;
           String plainBody = templateId[0].Body;
         
          
          // Messaging.sendEmail(new Messaging.Singleemailmessage[] {mail});
     @TestVisible Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.toAddresses = emailsAsArray;
            message.optOutPolicy = 'FILTER';
            message.subject = 'Opt Out Test Message';
            //message.plainTextBody = 'This is the message body.';
             if(templateId[0].id != null)
             message.setTemplateId(templateId[0].id);
             if(wideEmailAddressId!=Null)
             message.setOrgWideEmailAddressID(wideEmailAddressId);
             message.setSubject(subject);
             message.setHtmlBody(htmlBody);
             message.setPlainTextBody(plainBody);
            // message.setTreatBodiesAsTemplate(true);
            Messaging.SingleEmailMessage[] messages =  new List<Messaging.SingleEmailMessage> {message};
            System.debug('___________msg____' +messages );
            Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
            if (results[0].success) {
                System.debug('The email was sent successfully.');
            } else {
                System.debug('The email failed to send: '+ results[0].errors[0].message);
            } 
             
           }
         }
    }

}
AbhishekAbhishek (Salesforce Developers) 
The error “System. NullPointerException: Attempt to de-reference a null object” normally occurs when you try to reference an object which has not been initialized or has null values. To avoid this you need to make sure that all the sObjects in your class are initialized, preferably in the constructor.


Try the suggestions as mentioned below,
https://help.salesforce.com/articleView?id=000327918&type=1&mode=1


Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks.
Hanna BergsmaHanna Bergsma
Abhishek ,

Thank you. I have previously read this article and I have tried various places to do this try/catch in my statesment above but can never get them to save, ie I am using it incorrectly. 

I have read many many forums, any input on my actual code would be greatly appreciated!
sachinarorasfsachinarorasf
Hi Abhishek,
The error “System. NullPointerException: Attempt to de-reference a null object” normally occurs when we try to retrieve the value which contains null. So You need to apply a null check when you are going to use any list of objects, set of ids, and objects.
eg:
Set<Id> objAcc = new Set<Id>();
 for(Order objOr : objOrder){
    if(objOr.AccountId != null){
       objAcc.add(objOr.AccountId);
     }
 }

I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.
Thanks and Regards,
Sachin Arora
www.sachinsf.com