+ Start a Discussion
FinneyFinney 

Help please - System.NullPointerException: Attempt to de-reference a null object

I am getting an error on the following trigger.Will mark the error line in bold.
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) {

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    
   if((Trigger.isBefore && Trigger.isUpdate) || (Trigger.isBefore && Trigger.isUpdate) ){  
   
    for(Contract cont : Trigger.New){
        accountIds.add(cont.AccountId);
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
   
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_Emirates_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds LIMIT 1]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    if(contactIds.size() > 0) conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contact where Id = :contactIds]);
   
D-CoderD-Coder
On which line you are geeting error ? Please share more details.
HARSHIL PARIKH AKA:GovindHARSHIL PARIKH AKA:Govind
Try using the following trigger:
trigger OTC_TrgPopulateKeyContactDetails on Contract (before insert,before update) 
{

    List<Id> accountIds = new List<Id>(); 
    List<Id> contactIds = new List<Id>();
    
   if((Trigger.isBefore && Trigger.isUpdate) || (Trigger.isBefore && Trigger.isUpdate) )
    {  
   
    for(Contract cont : Trigger.New)
    {
        If(cont.AccountId != null)
        {
            accountIds.add(cont.AccountId);
        }
        
        
        if(cont.Key_Contact__c != null)
            contactIds.add(cont.Key_Contact__c);
    }
   
    Map<Id,Account> accMap = new Map<Id,Account>([Select Id,Name,PersonEmail,Passport__pc,OTC_Emirates_ID_Upload__pc,PersonMobilePhone,Phone,IsPersonAccount,FirstName,LastName,(Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contacts where OTC_Key_Contact__c = true) from Account where Id = :accountIds LIMIT 1]);
    Map<Id,Contact> conMap = new Map<Id,Contact>();
    
    if(contactIds.size() > 0) 
    
    conMap = new Map<Id,Contact>([Select Id,Email,MobilePhone,FirstName,LastName,Phone,Passport__c,OTC_Emirates_ID_Upload__c from Contact where Id = :contactIds]);
    }
}
I have just checked the condition for if the when cont.AccountId != null then only add accountIds.add(cont.AccountId)

Hope this helps!
 
FinneyFinney
Hi, I have got the issue resolved by using the try catch block.

I couldn't post the complete code here due to restrictions on character count.

Thanks for trying to help me :)