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
Colby FlyeColby Flye 

NullPointerException De-Reference A Null Object

Hi Everyone!

I get to write my first apex class! Yay! I am running into a NullPointerException De-Reference A Null Object error. My method is being called in an afterTrigger, please look below...

public static void updatenewCaseRecordTeamFields(List<Case> cases){
    map<Case, Id> CasetoUser = new map<Case,Id>();
    map<Id, User> UserIdtoUser = new map<Id,User>();
    List<Id> OwnerIds = new List<Id>();
        for(Case c:(List<Case>)trigger.new){
            If(c.Owner.Type=='User' && c.OwnerId != null){
               OwnerIds.add(c.OwnerId);
               CasetoUser.put(c,c.OwnerId);
            }
        }
               List<User> userList = [SELECT team__c from User where Id IN: OwnerIds];
            For(User u: userList){
                UserIdtoUser.put(u.Id,u);
            }
                for(Case c:(List<Case>)trigger.new){
                    c.CaseOpenedTeam__c = UserIdtoUser.get(CasetoUser.get(c)).team__c;
                    c.CaseOwnerTeam__c = UserIdtoUser.get(CasetoUser.get(c)).team__c;               
                }
        
    }
The run down is that the code is trying to set fields on case fields based on the Owner of the record, being the user, and update those fields with the users teams. 

Thanks in Advance!
Hemant_SoniHemant_Soni
Hi Colby,
I have made few changes in you trigger. Please try below one.
public static void updatenewCaseRecordTeamFields(List<Case> cases){
	map<Id, User> UserIdtoUser = new map<Id,User>();
	Set<Id> OwnerIds = new Set<Id>();
	for(Case c : (List<Case>)trigger.new){
		If(c.Owner.Type=='User' && c.OwnerId != null){
			OwnerIds.add(c.OwnerId);
		}
	}
	for(User oUser : [SELECT team__c from User where Id IN: OwnerIds]){
		UserIdtoUser.put(u.Id, u);
	}
	if(!UserIdtoUser.isEmpty()){
		for(Case c : (List<Case>)trigger.new){
			if(UserIdtoUser.containsKey(c.OwnerId)){
				c.CaseOpenedTeam__c = UserIdtoUser.get(c.OwnerId).team__c;
				c.CaseOwnerTeam__c = UserIdtoUser.get(c.OwnerId).team__c;   
			}
		}
	}
	}
For understanding of code you can simply compare your and mine code.
For further assistance you can directly contact to me on my gmail.
Thanks
Hemant
Email : sonihemant.jaipur@gmail.com