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
krishna3krishna3 

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

Hi everyone, 

i am trying to update otc Contact records.

i have a field called contact status. when i am trying to update the records with status change, its only updating few reocrds and getting the following error for the other records.

 

 

 execution of AfterUpdate  caused by: System.NullPointerException: Attempt to de-reference a null object  Trigger.UpdatePrimaryUnitOTCContact: line 42, column 30"

 

 

trigger UpdatePrimaryUnitOTCContact on OTC_Contact__c (after insert, after update) {

    List <String> UnitIds= new List<String>();
     For(OTC_Contact__c otc : trigger.new)
     {
       UnitIds.add(otc.Unit__c);
     }
     List<Unit__c>Units = [Select Id, Name, Primary_OTC_Contact__c From Unit__c Where id IN:UnitIds];
     Map<String,Unit__c>UnitMap = New Map<String,Unit__c>(); 
     For(Unit__c ut : Units)
     {
       UnitMap.Put(ut.id, ut);
     }
     Map<id,Unit__c> UnitUpdates = New Map<Id,Unit__c>();
     For(OTC_Contact__c otc : Trigger.new)
     {
       system.debug('Entered for loop');
        if(otc.Is_Primary_Unit_Contact__c==TRUE)
        {
         Unit__c un = UnitMap.get(otc.Unit__c);
                
                system.debug(un.Id);// this is the line i am getting error
                un.Primary_OTC_Contact__c=otc.id;
                UnitUpdates.put(un.id,un);
        }
     }
   update UnitUpdates.values();    
}

 

when i try to comment out that line i am getting an error below the line.

 

can anyone help me out in this..  its urgent 

 

thanks in advance...

bob_buzzardbob_buzzard

The reason for the error is that the value of 'un'  you have retrieved from the Map is null, so when you try to acess a field on 'un', you are dereferencing a null pointer and that is not allowed.

 

Why this is null is a little more interesting, it looks like you are setting up the map correctly, so I'd surmise that you have one or more OTC_Contact__c records in trigger.new that have a Unit__c field that is null.  A key value of null is valid for a map, so your attempt to extract the associated value from the map will complete, but the value will be null.

 

You can just null protect this piece of code, but that may not be the right solution for your use case:

 

 

 Unit__c un = UnitMap.get(otc.Unit__c);
 if (null!=un)
 {
    system.debug(un.Id);// this is the line i am getting error
    un.Primary_OTC_Contact__c=otc.id;
    UnitUpdates.put(un.id,un);
 }