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
AbhishekJAbhishekJ 

I am getting NullPointerException error while saving a new contact record.

I am getting NullPointerException error while saving a new contact record.
Here is the exact error message:
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger ContactTrigger caused an unexpected exception, contact your administrator: ContactTrigger: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: ()

I am new to apex coding and this code isn't written by me, so finding it hard to troubleshoot the issue. Would anyone be able to help?
Here is Apex Trigger:
trigger ContactTrigger on Contact (before delete, after insert, after update,after delete,after undelete) { 
    if(Trigger.isAfter) {
            if(Trigger.isUpdate) {
            ContactTriggerHandler.onAfterUpdate(Trigger.new,Trigger.oldMap);
            }
            
            if(Trigger.isInsert){
             ContactTriggerHandler.OnAfterInsert(Trigger.new);
            }
            
            if(Trigger.IsDelete){
                ContactTriggerHandler.OnAfterDelete(Trigger.old);
            }
            
            if(Trigger.IsUnDelete){
                ContactTriggerHandler.OnUndelete(Trigger.new);
            }
    }
    if(Trigger.isBefore){
            if(Trigger.IsDelete){
            }
    }
}

And here is the Apex Class:
public class ContactTriggerHandler {
    
    public static void onAfterUpdate(List<Contact> newContacts, Map<id,Contact> oldContacts) {
            updateSortedCorrespondencePreferneceData(newContacts,oldContacts);
            updateSalutationOnCommunicationContent(newContacts,oldContacts); 
            id cpCapitalPartnerRT = fetchRecordTypeId('Account','CP Capital Partner');
            List<Contact> newList = new List<Contact>();
            
            set<Id> oldAndNewAccountIds = new set<id>();
            for(Contact con : newContacts) {
                oldAndNewAccountIds.add(con.accountId);
                oldAndNewAccountIds.add(oldContacts.get(con.id).accountId);
            }
            
            Map<Id,Account> accountDetails = new Map<Id,Account>([Select Id,RecordTypeId from Account where Id in :oldAndNewAccountIds]);
            for(Contact con : newContacts) {
                    if(accountDetails !=NULL && con!= Null && con.accountId != oldContacts.get(con.Id).accountId  ) { 
                        if(  accountDetails.containsKey(con.accountId) && (accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT || accountDetails.get(oldContacts.get(con.Id).accountId).recordTypeId == cpCapitalPartnerRT) ) {
                            newList.add(con);
                        }

                    } else if(accountDetails !=NULL && con!= Null && accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT ) {  
                        newList.add(con);
                    }
            }        
           
            Email_InformationClass.getEmailTableData(newList,oldContacts); 
			
            updateCPIntralinksAccess(newContacts,oldContacts);
			
    }
    
	
    public static void OnAfterDelete(contact[] oldList){
        
        updateCPIntralinksAccess(oldList, null);
    }
    
     public static void OnAfterInsert(contact[] newList){
        
        updateCPIntralinksAccess(newList, null);
    }
     
    public static void OnUndelete(contact[] newList){ 
         
         updateCPIntralinksAccess(newList,null);
    }
	
    private static void updateSalutationOnCommunicationContent(List<Contact> newContacts, Map<id,Contact> oldContacts){
        set<id> contactsToProcess = new set<id>();

        for(Contact con : newContacts) {
		
            if((String.isNotBlank(con.email) && !con.email.contains('@generalatlantic.com'))  && ((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
                                                                                                  (con.FirstName != oldContacts.get(con.id).FirstName)) || (con.International_Salutation_Type__c!= oldContacts.get(con.Id).International_Salutation_Type__c || String.isBlank(oldContacts.get(con.Id).email))
              )
			  
            {
                
                        contactsToProcess.add(con.id);
            }
        }
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Company__c, RecordType.Name from Correspondence_Preference__c where Recipient_Type__c = 'To' AND Contact__c In :contactsToProcess]);
            set<string> cpNames = new Set<String>();
            set<string> accountNames = new Set<String>();
            for(Correspondence_Preference__c cp : corrPrefToProcess) {
                cpNames.add(cp.RecordType.Name);
                accountNames.add(cp.Company__c);
            }
            List<Communications_Content__c> ccList = new List<Communications_Content__c>([Select Id,Salutation__c,Company__c,Correspondence_Preference__c from Communications_Content__c where Company__c IN :accountNames AND Correspondence_Preference__c IN :cpNames]);
            CommunicationContentTriggerHandler handler = new CommunicationContentTriggerHandler(true,200,true);
            handler.updateSalutationField(null,ccList); 
        }
		
    private static void updateSortedCorrespondencePreferneceData(List<Contact> newContacts, Map<id,Contact> oldContacts) {
        set<id> contactsToProcess = new set<id>();
        for(Contact con : newContacts) {
            if((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
               (con.Email != oldContacts.get(con.id).Email)
              ) {
                  contactsToProcess.add(con.id);
              }
        }
        
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Commitment__c, RecordTypeId from Correspondence_Preference__c where Contact__c In :contactsToProcess]);
            
            CorrespondenceTriggerHandler.getCommRecTypeData(corrPrefToProcess,null,false);
        }
    }
	
    private static id fetchRecordTypeId(string sObj, string rt) {
        System.debug('fetch params>>'+sObj + '<<<rt>>>'+rt);
        String recordtypeId = Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId(); 
        return Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId();
		
    }
	
    public static void updateCPIntralinksAccess(List<Contact> newContacts, Map<id,Contact> OldMap){
        
        Map<ID,List<contact>> mapConWithAcc = new Map<ID,List<contact>>();
        List<account> accList = new List<account>();
        String temp= '';
        Map<Id,String> accUpdateMap = new Map<Id,String>();
        Set<ID> accid = new Set<ID>();
        
        for(contact con: newContacts){
            if(oldMap == null || (oldMap.get(con.id).CP_Intralinks_Access__c != con.CP_Intralinks_Access__c)){ 
                accid.add(con.accountid); 
            }
            if(oldMap.get(con.Id).AccountId != con.AccountId)
            {
               accid.add(con.AccountId);
               accid.add(oldMap.get(con.Id).AccountId);
            }
        }
        

		
        for(Account acc : [Select id,CP_Intralinks_Access__c,(Select id,CP_Intralinks_Access__c,accountid from contacts) from account where id in :accid]) {
            set<string> val = new set<string>();
            String finalVal = '' ;
            for(Contact ct : acc.contacts) {
                if(String.isNOtBlank(ct.CP_Intralinks_Access__c)) {
                    val.addAll(ct.CP_Intralinks_Access__c.split(';')); 
                }
            }
            List<String> valList = new List<String>();
            valList.addAll(val);
            if(valList.size() > 0) {
                finalVal = String.join(valList,',');
            }
            acc.CP_Intralinks_Access__c = finalVal ;
            accList.add(acc);
        }
        if(accList.size() > 0) {
            update accList ;
        }
    }
}

 
Best Answer chosen by AbhishekJ
Deepali KulshresthaDeepali Kulshrestha
Hi ,
Greetings to you!

I have gone through your problem and I found you are passing null in the second parameter when you are calling updateCPIntralinksAccess method from inside OnAfterInsert method and you have a null applied null check for oldMap variable in updateCPIntralinksAccess method .So when oldMap variable is null you can extract value by applying dot(.) .That's the reason for the null pointer exception. I have applied null check in your code and commented a line for you to understand.
public class ContactTriggerHandler {
    
    public static void onAfterUpdate(List<Contact> newContacts, Map<id,Contact> oldContacts) {
            updateSortedCorrespondencePreferneceData(newContacts,oldContacts);
            updateSalutationOnCommunicationContent(newContacts,oldContacts); 
            id cpCapitalPartnerRT = fetchRecordTypeId('Account','CP Capital Partner');
            List<Contact> newList = new List<Contact>();
            
            set<Id> oldAndNewAccountIds = new set<id>();
            for(Contact con : newContacts) {
                oldAndNewAccountIds.add(con.accountId);
                oldAndNewAccountIds.add(oldContacts.get(con.id).accountId);
            }
            
            Map<Id,Account> accountDetails = new Map<Id,Account>([Select Id,RecordTypeId from Account where Id in :oldAndNewAccountIds]);
            for(Contact con : newContacts) {
                    if(accountDetails !=NULL && con!= Null && con.accountId != oldContacts.get(con.Id).accountId  ) { 
                        if(  accountDetails.containsKey(con.accountId) && (accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT || accountDetails.get(oldContacts.get(con.Id).accountId).recordTypeId == cpCapitalPartnerRT) ) {
                            newList.add(con);
                        }

                    } else if(accountDetails !=NULL && con!= Null && accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT ) {  
                        newList.add(con);
                    }
            }        
           
            Email_InformationClass.getEmailTableData(newList,oldContacts); 
            
            updateCPIntralinksAccess(newContacts,oldContacts);
            
    }
    
    
    public static void OnAfterDelete(contact[] oldList){
        
        updateCPIntralinksAccess(oldList, null);
    }
    
     public static void OnAfterInsert(contact[] newList){
        
        updateCPIntralinksAccess(newList, null);
    }
     
    public static void OnUndelete(contact[] newList){ 
         
         updateCPIntralinksAccess(newList,null);
    }
    
    private static void updateSalutationOnCommunicationContent(List<Contact> newContacts, Map<id,Contact> oldContacts){
        set<id> contactsToProcess = new set<id>();

        for(Contact con : newContacts) {
        
            if((String.isNotBlank(con.email) && !con.email.contains('@generalatlantic.com'))  && ((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
                                                                                                  (con.FirstName != oldContacts.get(con.id).FirstName)) || (con.International_Salutation_Type__c!= oldContacts.get(con.Id).International_Salutation_Type__c || String.isBlank(oldContacts.get(con.Id).email))
              )
              
            {
                
                        contactsToProcess.add(con.id);
            }
        }
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Company__c, RecordType.Name from Correspondence_Preference__c where Recipient_Type__c = 'To' AND Contact__c In :contactsToProcess]);
            set<string> cpNames = new Set<String>();
            set<string> accountNames = new Set<String>();
            for(Correspondence_Preference__c cp : corrPrefToProcess) {
                cpNames.add(cp.RecordType.Name);
                accountNames.add(cp.Company__c);
            }
            List<Communications_Content__c> ccList = new List<Communications_Content__c>([Select Id,Salutation__c,Company__c,Correspondence_Preference__c from Communications_Content__c where Company__c IN :accountNames AND Correspondence_Preference__c IN :cpNames]);
            CommunicationContentTriggerHandler handler = new CommunicationContentTriggerHandler(true,200,true);
            handler.updateSalutationField(null,ccList); 
        }
        
    private static void updateSortedCorrespondencePreferneceData(List<Contact> newContacts, Map<id,Contact> oldContacts) {
        set<id> contactsToProcess = new set<id>();
        for(Contact con : newContacts) {
            if((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
               (con.Email != oldContacts.get(con.id).Email)
              ) {
                  contactsToProcess.add(con.id);
              }
        }
        
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Commitment__c, RecordTypeId from Correspondence_Preference__c where Contact__c In :contactsToProcess]);
            
            CorrespondenceTriggerHandler.getCommRecTypeData(corrPrefToProcess,null,false);
        }
    }
    
    private static id fetchRecordTypeId(string sObj, string rt) {
        System.debug('fetch params>>'+sObj + '<<<rt>>>'+rt);
        String recordtypeId = Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId(); 
        return Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId();
        
    }
    
    public static void updateCPIntralinksAccess(List<Contact> newContacts, Map<id,Contact> OldMap){
        
        Map<ID,List<contact>> mapConWithAcc = new Map<ID,List<contact>>();
        List<account> accList = new List<account>();
        String temp= '';
        Map<Id,String> accUpdateMap = new Map<Id,String>();
        Set<ID> accid = new Set<ID>();
        
        for(contact con: newContacts){
            /* Added null chech after or*/
            if(oldMap == null || (oldMap != Null && oldMap.get(con.id).CP_Intralinks_Access__c != con.CP_Intralinks_Access__c)){ 
                accid.add(con.accountid); 
            }
            /* Added null chech below*/
            if(oldMap != Null && oldMap.get(con.Id).AccountId != con.AccountId)
            {
               accid.add(con.AccountId);
               accid.add(oldMap.get(con.Id).AccountId);
            }
        }
        

        
        for(Account acc : [Select id,CP_Intralinks_Access__c,(Select id,CP_Intralinks_Access__c,accountid from contacts) from account where id in :accid]) {
            set<string> val = new set<string>();
            String finalVal = '' ;
            for(Contact ct : acc.contacts) {
                if(String.isNOtBlank(ct.CP_Intralinks_Access__c)) {
                    val.addAll(ct.CP_Intralinks_Access__c.split(';')); 
                }
            }
            List<String> valList = new List<String>();
            valList.addAll(val);
            if(valList.size() > 0) {
                finalVal = String.join(valList,',');
            }
            acc.CP_Intralinks_Access__c = finalVal ;
            accList.add(acc);
        }
        if(accList.size() > 0) {
            update accList ;
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha

All Answers

Deepali KulshresthaDeepali Kulshrestha
Hi ,
Greetings to you!

I have gone through your problem and I found you are passing null in the second parameter when you are calling updateCPIntralinksAccess method from inside OnAfterInsert method and you have a null applied null check for oldMap variable in updateCPIntralinksAccess method .So when oldMap variable is null you can extract value by applying dot(.) .That's the reason for the null pointer exception. I have applied null check in your code and commented a line for you to understand.
public class ContactTriggerHandler {
    
    public static void onAfterUpdate(List<Contact> newContacts, Map<id,Contact> oldContacts) {
            updateSortedCorrespondencePreferneceData(newContacts,oldContacts);
            updateSalutationOnCommunicationContent(newContacts,oldContacts); 
            id cpCapitalPartnerRT = fetchRecordTypeId('Account','CP Capital Partner');
            List<Contact> newList = new List<Contact>();
            
            set<Id> oldAndNewAccountIds = new set<id>();
            for(Contact con : newContacts) {
                oldAndNewAccountIds.add(con.accountId);
                oldAndNewAccountIds.add(oldContacts.get(con.id).accountId);
            }
            
            Map<Id,Account> accountDetails = new Map<Id,Account>([Select Id,RecordTypeId from Account where Id in :oldAndNewAccountIds]);
            for(Contact con : newContacts) {
                    if(accountDetails !=NULL && con!= Null && con.accountId != oldContacts.get(con.Id).accountId  ) { 
                        if(  accountDetails.containsKey(con.accountId) && (accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT || accountDetails.get(oldContacts.get(con.Id).accountId).recordTypeId == cpCapitalPartnerRT) ) {
                            newList.add(con);
                        }

                    } else if(accountDetails !=NULL && con!= Null && accountDetails.get(con.accountId).recordTypeId == cpCapitalPartnerRT ) {  
                        newList.add(con);
                    }
            }        
           
            Email_InformationClass.getEmailTableData(newList,oldContacts); 
            
            updateCPIntralinksAccess(newContacts,oldContacts);
            
    }
    
    
    public static void OnAfterDelete(contact[] oldList){
        
        updateCPIntralinksAccess(oldList, null);
    }
    
     public static void OnAfterInsert(contact[] newList){
        
        updateCPIntralinksAccess(newList, null);
    }
     
    public static void OnUndelete(contact[] newList){ 
         
         updateCPIntralinksAccess(newList,null);
    }
    
    private static void updateSalutationOnCommunicationContent(List<Contact> newContacts, Map<id,Contact> oldContacts){
        set<id> contactsToProcess = new set<id>();

        for(Contact con : newContacts) {
        
            if((String.isNotBlank(con.email) && !con.email.contains('@generalatlantic.com'))  && ((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
                                                                                                  (con.FirstName != oldContacts.get(con.id).FirstName)) || (con.International_Salutation_Type__c!= oldContacts.get(con.Id).International_Salutation_Type__c || String.isBlank(oldContacts.get(con.Id).email))
              )
              
            {
                
                        contactsToProcess.add(con.id);
            }
        }
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Company__c, RecordType.Name from Correspondence_Preference__c where Recipient_Type__c = 'To' AND Contact__c In :contactsToProcess]);
            set<string> cpNames = new Set<String>();
            set<string> accountNames = new Set<String>();
            for(Correspondence_Preference__c cp : corrPrefToProcess) {
                cpNames.add(cp.RecordType.Name);
                accountNames.add(cp.Company__c);
            }
            List<Communications_Content__c> ccList = new List<Communications_Content__c>([Select Id,Salutation__c,Company__c,Correspondence_Preference__c from Communications_Content__c where Company__c IN :accountNames AND Correspondence_Preference__c IN :cpNames]);
            CommunicationContentTriggerHandler handler = new CommunicationContentTriggerHandler(true,200,true);
            handler.updateSalutationField(null,ccList); 
        }
        
    private static void updateSortedCorrespondencePreferneceData(List<Contact> newContacts, Map<id,Contact> oldContacts) {
        set<id> contactsToProcess = new set<id>();
        for(Contact con : newContacts) {
            if((con.Seniority_Rank__c != oldContacts.get(con.Id).Seniority_Rank__c) ||
               (con.Email != oldContacts.get(con.id).Email)
              ) {
                  contactsToProcess.add(con.id);
              }
        }
        
        if(contactsToProcess.size() > 0) {
            List<Correspondence_Preference__c> corrPrefToProcess = new List<Correspondence_Preference__c>([Select Id, Commitment__c, RecordTypeId from Correspondence_Preference__c where Contact__c In :contactsToProcess]);
            
            CorrespondenceTriggerHandler.getCommRecTypeData(corrPrefToProcess,null,false);
        }
    }
    
    private static id fetchRecordTypeId(string sObj, string rt) {
        System.debug('fetch params>>'+sObj + '<<<rt>>>'+rt);
        String recordtypeId = Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId(); 
        return Schema.getGlobalDescribe().get(sObj).getDescribe().getRecordTypeInfosByName().get(rt).getRecordTypeId();
        
    }
    
    public static void updateCPIntralinksAccess(List<Contact> newContacts, Map<id,Contact> OldMap){
        
        Map<ID,List<contact>> mapConWithAcc = new Map<ID,List<contact>>();
        List<account> accList = new List<account>();
        String temp= '';
        Map<Id,String> accUpdateMap = new Map<Id,String>();
        Set<ID> accid = new Set<ID>();
        
        for(contact con: newContacts){
            /* Added null chech after or*/
            if(oldMap == null || (oldMap != Null && oldMap.get(con.id).CP_Intralinks_Access__c != con.CP_Intralinks_Access__c)){ 
                accid.add(con.accountid); 
            }
            /* Added null chech below*/
            if(oldMap != Null && oldMap.get(con.Id).AccountId != con.AccountId)
            {
               accid.add(con.AccountId);
               accid.add(oldMap.get(con.Id).AccountId);
            }
        }
        

        
        for(Account acc : [Select id,CP_Intralinks_Access__c,(Select id,CP_Intralinks_Access__c,accountid from contacts) from account where id in :accid]) {
            set<string> val = new set<string>();
            String finalVal = '' ;
            for(Contact ct : acc.contacts) {
                if(String.isNOtBlank(ct.CP_Intralinks_Access__c)) {
                    val.addAll(ct.CP_Intralinks_Access__c.split(';')); 
                }
            }
            List<String> valList = new List<String>();
            valList.addAll(val);
            if(valList.size() > 0) {
                finalVal = String.join(valList,',');
            }
            acc.CP_Intralinks_Access__c = finalVal ;
            accList.add(acc);
        }
        if(accList.size() > 0) {
            update accList ;
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
This was selected as the best answer
AbhishekJAbhishekJ
Thanks a lot Deepali!