Below trigger is to sum the Amount of Contacts and display in the Account object. Trigger is working fine for insert, delete, and undelete. But while updating the Contact, I am getting the below error:
Apex trigger contactAmountSum caused an unexpected exception, contact your administrator: contactAmountSum: execution of AfterUpdate caused by: System.NullPointerException: Argument cannot be null.: Trigger.contactAmountSum: line 21, column 1
What might be the issue?
trigger contactAmountSum on Contact (after insert, after delete, after undelete, after update) {
set<Id> accIdSet = new set<Id>();
if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
for(Contact conObj: Trigger.new){
if(Trigger.isInsert || Trigger.isUndelete || (conObj.Amounts__c != Trigger.oldMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.oldMap.get(conObj.Id).AccountId))
accIdSet.add(conObj.AccountId);
}
}
if(trigger.isUpdate || trigger.isDelete) {
for(Contact conObj: Trigger.old){
if(Trigger.isDelete || (conObj.Amounts__c != Trigger.newMap.get(conObj.Id).Amounts__c || conObj.AccountId != Trigger.newMap.get(conObj.Id).AccountId))
accIdSet.add(conObj.AccountId);
}
}
List<Account> accList = [select id, Amounts__c, (Select Id, Amounts__c from contacts) from Account Where ID IN: accIdSet];
for(Account acc : accList){
acc.Amounts__c = 0;
for(Contact conObj : acc.contacts) {
acc.Amounts__c += conObj.Amounts__c; // here getting null pointer exception
}
}
update accList;
}