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
Travis Malle 9Travis Malle 9 

NullPointerException

Hello All,
Tried writing a trigger to count donations where the account ID is listed in a reference field but am getting a null pointer error. been looking at this thing for a while and need another pair of eyes on it. I’m still really new to apex in general and am trying to learn. If someone could give me some guidance it would be great appreciated.
 
trigger CountDonations on Donation__c (after insert, after update, after delete) 
{
	set <ID> accountInTriggerSet = new set <ID>();
    set <ID> childAccountSet = new set <ID>();
    
    
    for(Donation__c don : Trigger.new)
        {
            accountInTriggerSet.add(don.Organization__c);
        }
    
    for(account Acct : [SELECT id FROM Account WHERE Parent_site__c IN :accountInTriggerSet])
        {
            childAccountSet.add(acct.Id);
        }
    
    Map <id, aggregateResult> ChildDonationSumMap = new map <id, aggregateResult>([SELECT organization__c AcctID, Sum(Donation_Amount__c)DonSum 
                                                                                   FROM Donation__c 
                                                                                   WHERE organization__C != null 
                                                                                   AND ID IN :childAccountSet 
                                                                                   GROUP BY organization__c]);
    
    
    List <account> updatedAccounts = [SELECT ID, name, Sum_Of_Child_Donations__C FROM account where ID IN :AccountInTriggerSet];
    
    for (account acct : UpdatedAccounts)
    {
        acct.Sum_of_Child_Donations__c = (decimal)childDonationSumMap.get(acct.id).get('DonSum');
        
    }
    update updatedAccounts;

}

 
Best Answer chosen by Travis Malle 9
Mahesh DMahesh D
Hi Travis,

Please find the below code which I corrected by following the best practices:
 
trigger CountDonations on Donation__c (after insert, after update, after delete) {
	set <ID> accountInTriggerSet = new set <ID>();
    set <ID> childAccountSet = new set <ID>();
    
    for(Donation__c don : Trigger.new) {
		if(don.Organization__c != null)
			accountInTriggerSet.add(don.Organization__c);
	}
    
	if(!accountInTriggerSet.isEmpty()) {
		for(Account Acct : [SELECT id FROM Account WHERE Parent_site__c IN :accountInTriggerSet]) {
			childAccountSet.add(acct.Id);
		}
		
		if(!childAccountSet.isEmpty()) {
			Map <id, aggregateResult> ChildDonationSumMap = new map <id, aggregateResult>([SELECT organization__c AcctID, Sum(Donation_Amount__c)DonSum FROM Donation__c 
				WHERE organization__C != null AND ID IN :childAccountSet GROUP BY organization__c]);
			
			List <account> updatedAccounts = [SELECT ID, name, Sum_Of_Child_Donations__C FROM account where ID IN :accountInTriggerSet];
			
			for (account acct : UpdatedAccounts) {
				if(childDonationSumMap.get(acc.Id) != null)
					acct.Sum_of_Child_Donations__c = (decimal)childDonationSumMap.get(acct.id).get('DonSum');
			}
			update updatedAccounts;
		}
	}
}

I would like to ask you onething here

childAccountSet contains the set of account ids and you are trying to use it in retrieving Donation__c record by using the where condition of ID IN: childAccountSet.

Which will not work because both are SFDC IDs and which will not match at any scenario.

Please do let me know if it helps you.

Regards,
Mahesh


 

All Answers

Sumit Kumar Singh 9Sumit Kumar Singh 9
Hello Travis,

You haven't mentioned at which line you are getting NULL pointer exception - 
I am suspecting that while retriving the values from the map, you would be getting this - 
Just, add one more line, see if it helps you. 
 
for (account acct : UpdatedAccounts)
    {
	    if(childDonationSumMap != null && childDonationSumMap.get(acct.id)!= null) {
			acct.Sum_of_Child_Donations__c = (decimal)childDonationSumMap.get(acct.id).get('DonSum');
		}      
    }

Thanks,
Sumit Kuamr Singh
Mahesh DMahesh D
Hi Travis,

Please find the below code which I corrected by following the best practices:
 
trigger CountDonations on Donation__c (after insert, after update, after delete) {
	set <ID> accountInTriggerSet = new set <ID>();
    set <ID> childAccountSet = new set <ID>();
    
    for(Donation__c don : Trigger.new) {
		if(don.Organization__c != null)
			accountInTriggerSet.add(don.Organization__c);
	}
    
	if(!accountInTriggerSet.isEmpty()) {
		for(Account Acct : [SELECT id FROM Account WHERE Parent_site__c IN :accountInTriggerSet]) {
			childAccountSet.add(acct.Id);
		}
		
		if(!childAccountSet.isEmpty()) {
			Map <id, aggregateResult> ChildDonationSumMap = new map <id, aggregateResult>([SELECT organization__c AcctID, Sum(Donation_Amount__c)DonSum FROM Donation__c 
				WHERE organization__C != null AND ID IN :childAccountSet GROUP BY organization__c]);
			
			List <account> updatedAccounts = [SELECT ID, name, Sum_Of_Child_Donations__C FROM account where ID IN :accountInTriggerSet];
			
			for (account acct : UpdatedAccounts) {
				if(childDonationSumMap.get(acc.Id) != null)
					acct.Sum_of_Child_Donations__c = (decimal)childDonationSumMap.get(acct.id).get('DonSum');
			}
			update updatedAccounts;
		}
	}
}

I would like to ask you onething here

childAccountSet contains the set of account ids and you are trying to use it in retrieving Donation__c record by using the where condition of ID IN: childAccountSet.

Which will not work because both are SFDC IDs and which will not match at any scenario.

Please do let me know if it helps you.

Regards,
Mahesh


 
This was selected as the best answer
Travis Malle 9Travis Malle 9
Hello Mahesh,

Thank you for taking the time to review. Can you help me understand IN condition will not work. I understand they are both id's
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
trigger CountDonations on Donation__c (after insert, after update, after delete) 
{
	set <ID> accountInTriggerSet = new set <ID>();
    set <ID> childAccountSet = new set <ID>();
    
    
    for(Donation__c don : Trigger.new)
	{
		if(don.Organization__c != null)
		{
			accountInTriggerSet.add(don.Organization__c);
		}	
	}
    
    for( account Acct : [SELECT id FROM Account WHERE Parent_site__c IN :accountInTriggerSet] )
	{
		childAccountSet.add(acct.Id);
	}
    
    Map <id, aggregateResult> ChildDonationSumMap = new map <id, aggregateResult>([SELECT organization__c AcctID, Sum(Donation_Amount__c) DonSum 
                                                                                   FROM Donation__c 
                                                                                   WHERE organization__C != null 
                                                                                   AND ID IN :childAccountSet 
                                                                                   GROUP BY organization__c]);
    
    
    List <account> updatedAccounts = [SELECT ID, name, Sum_Of_Child_Donations__C FROM account where ID IN :AccountInTriggerSet];
    List<Account> accountToUpdate = new List<Account>();
	
    for (account acct : UpdatedAccounts)
    {
		if(childDonationSumMap.containsKey(acct.id)) // Please always try to use containsKey to check key in map
		{
			acct.Sum_of_Child_Donations__c = (decimal)childDonationSumMap.get(acct.id).get('DonSum');
			accountToUpdate.add(acct);
		}
    }

	if(accountToUpdate.size() > 0 )
	{
		update accountToUpdate;
	}
}

Let us know if this will help you.
1) One Trigger Per Object
A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

2) Logic-less Triggers
If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3) Context-Specific Handler Methods
Create context-specific handler methods in Trigger handlers


4) Bulkify your Code
Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5) Avoid SOQL Queries or DML statements inside FOR Loops
An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

6) Using Collections, Streamlining Queries, and Efficient For Loops
It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

7) Querying Large Data Sets
The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

8) Use @future Appropriately
It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

9) Avoid Hardcoding IDs
When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
Mahesh DMahesh D
Hi Travis,

Generally Account Id and Donation__c Id are SFDC ids and those will never match.

for(Account Acct : [SELECT id FROM Account WHERE Parent_site__c IN :accountInTriggerSet]) {
            childAccountSet.add(acct.Id);
        }

Here you are capturing the Account Id Set.

Map <id, aggregateResult> ChildDonationSumMap = new map <id, aggregateResult>([SELECTorganization__c AcctID, Sum(Donation_Amount__c)DonSum FROM Donation__c
               WHERE organization__C != null AND ID IN :childAccountSet GROUP BYorganization__c]);

Here you are using the above childAccountSet which is actually Set of Account Ids which will never match and it will always return empty results.

Please do let me know if you it helps you.

Regards,
Mahesh