1

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;
}

2 Answers 2

0

conObj.Amounts__c seems to be null.

Can you try this one?

for(Contact conObj : acc.contacts) {
   if(conObj.Amounts__c != null){
       acc.Amounts__c += conObj.Amounts__c;
   }
}
1
  • can u plz let me know how to get max, min of contacts in the same query used in trigger. Commented Oct 25, 2019 at 10:51
0

If you want Max value and Min value, you can get by the below code.

acc.Amounts__c = 0;
acc.AmountsMax__c = 0;
acc.AmountsMin__c = 0;
for(Contact conObj : acc.contacts) {
   if(conObj.Amounts__c != null){
       acc.Amounts__c += conObj.Amounts__c;
       if(conObj.Amounts__c > acc.AmountsMax__c){
           acc.AmountsMax_c = conObj.Amounts__c;
       }
       if(conObj.Amounts__c < acc.AmountsMin__c){
           acc.AmountsMin_c = conObj.Amounts__c;
       } 
   }
}
1
  • acc.AmountsMin_c showing as zero "0" value Commented Nov 7, 2019 at 9:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .