+ Start a Discussion
NandhuNandhu 

I am getting error

LeavesTrigger: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id a0Wp0000002cmVZEAY; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeavesTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Class.TriggerHandlerLeave.afterUpdate: line 12, column 1 Trigger.LeavesTrigger: line 3, column 1: [] Class.TriggerHandlerLeave.afterUpdate: line 16, column 1 Trigger.LeavesTrigger: line 3, column 1

Trigger:trigger LeavesTrigger on Leaves__c (after update, after insert) {
  if (trigger.isAfter && trigger.isUpdate) {
    TriggerHandlerLeave.afterUpdate(Trigger.New);
   }    
}
public with sharing class TriggerHandlerLeave {
  
     public static void handlerAfterUpdate(List<Leaves__c> leaveList){
        Map<Id, Leaves__c> merMap = new Map<Id, Leaves__c>([Select Id, Name,Approval_Status__c,
                                                     Total_Leave__c,
                                                     Req_Days_Off__c 
                                                     From Leaves__c WHERE Approval_Status__c ='Approved']);         
        
         for(Leaves__c approvedList:leaveList){
            if(approvedList.Approval_Status__c =='Approved'){
          
               merMap.get(approvedList.Id).Total_Leave__c = merMap.get(approvedList.Id).Total_Leave__c - merMap.get(approvedList.Id).Req_Days_Off__c;
              
                }
           }      
               Insert merMap.values();
     }
}
test class:
@isTest
public with sharing class TestTriggerHandlerLeave {
    @isTest
    public static void testAfterInsert(){
        Leaves__c objLeave = new Leaves__c (Employee_Name__c='Nani',Approval_Status__c = 'Approved');       
        insert objLeave;
        
        Test.startTest();
        objLeave = new Leaves__c (Employee_Name__c='Nani',Approval_Status__c = 'Approved');
        Database.SaveResult result = Database.insert(objLeave, false);
        Test.stopTest();
    }

}
AnudeepAnudeep (Salesforce Developers) 
Hi Nandhu, 

Null pointer exceptions are usually thrown by a line of code that is trying to use an object that has not been instantiated, or an object's attribute that has not been initialized.

I see you have a list in the code. Please check for the presence of values before performing the query. You can use the isEmpty() attribute for both list and map

(https://help.salesforce.com/articleView?id=000327918&type=1&mode=1)

Anudeep