You need to sign in to do that
Don't have an account?

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.
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...
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: