public with sharing class UserTriggerMethod {
public static void updateAppDelegation(Map<ID,User> mapNewUser)
{
// get a list of emails for the newly inserted users
List<String> useremails = new List<String>();
for (User u : mapNewUser.values())
{
if(u.ContactId!=null)
{
useremails.add(u.email);
}
}
//query all Delegated contacts (and associated Application Delegations) at once
List<Delegated_Contact__c> lstdelegatedContact = [SELECT Id, Email__c,
(SELECT Contact__c from Application_Delegations__r)
FROM Delegated_Contact__c
WHERE Email__c in :useremails ];
//create a lookup from email to Delegated Contact
map<string, Delegated_Contact__c> mapemailToDelegatedContact= new map<String, Delegated_Contact__c>();
for(Delegated_Contact__c delgatedContact : lstdelegatedContact)
{
mapemailToDelegatedContact.put(delgatedContact.Email__c, delgatedContact);
}
List<Application_Delegation__c> lstAppDelegatedContoupdate;
List<Delegated_Contact__c> lstDelegatedContacttodelete;
for(User user : mapNewUser.values())
{
if(mapemailToDelegatedContact.containsKey(user.email))
{
Delegated_Contact__c delegatedContact = mapemailToDelegatedContact.get(user.email);
List<Application_Delegation__c> lstAppDelegatedContact = delegatedContact.Application_Delegations__r;
lstAppDelegatedContoupdate = new List<Application_Delegation__c>();
lstDelegatedContacttodelete = new List<Delegated_Contact__c>();
for(Application_Delegation__c AppDelegatedContact: lstAppDelegatedContact)
{
AppDelegatedContact.Contact__c = user.ContactId;
lstAppDelegatedContoupdate.add(AppDelegatedContact);
}
lstDelegatedContacttodelete.add(delegatedContact);
}
}
if(lstAppDelegatedContoupdate.size() > 0 && lstAppDelegatedContoupdate != null)
{
try
{
update lstAppDelegatedContoupdate;
}
catch(DMLException e)
{
system.debug(e.getMessage());
}
}
if(!lstDelegatedContacttodelete.IsEmpty())
{
delete lstDelegatedContacttodelete;
}
}
}
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UserTrigger caused an unexpected exception, contact your administrator: UserTrigger: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.UserTriggerMethod.updateAppDelegation: line 52, column 1
i.e Line :-
if(lstAppDelegatedContoupdate.size() > 0 && lstAppDelegatedContoupdate != null)
Best Answer
Write this line as:
It clearly shows that
lstAppDelegatedContoupdate
is assigned to null or not initialized.You code should throw
Null pointer
exception ifmapNewUser
is empty. Also you are initializing this list in for loop, only last iterated values will be updated.