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
_why the unlucky stiff_why the unlucky stiff 

Attempt to de reference a null object error!

Hello gentlemen, I am getting the famous 'attempt to de reference a null object error' when for this particular condition It is specifically happening because of this line - (comparing old value to new and making sure it's not the same). 

 

(opp.StageName != oldMap.get(opp.Id).StageName)

 

Here is the larger context - (line 11-12)

 

		// Declare Collections and variables
		final List<Opportunity> changedOpps = new List<Opportunity>();
		Set<Id> UserId = new Set<Id>();
		final String NewFleet = '012Q00000008rSIIAY';
		final String NewGovernment = '012Q00000008rSNIAY';
		
		// Create a map of Opportunities that are ClosedWon and have a particular RecordType
			System.debug('Before for loop');
		for (Opportunity opp : newMap.values()){
			System.debug('After length check: ' + newMap.Values());
			if ((opp.StageName != null) && (opp.StageName != oldMap.get(opp.Id).StageName)){
				System.debug('After length check 2: ' + opp.Name);
				if (opp.StageName == 'Closed Won') {
					System.debug('After Stage check: ' + opp.Name);
					if (opp.RecordTypeId == NewFleet|| opp.RecordTypeId == NewGovernment){
						System.debug('After RecordTypeCheck : ' + opp.Name);
						changedOpps.add(opp);
					}
				}
			}
		}

 

AmitSahuAmitSahu

If it is a before insert trigger then the line below if creating issue:

Unless the record is created in the system you wont get opp.Id hence the opp.id will be null in this case:

 

for (Opportunity opp : newMap.values())
_why the unlucky stiff_why the unlucky stiff

j020, it's for After insert trigger.

sfdcfoxsfdcfox

"Insert" triggers do not have a Trigger.old or Trigger.oldMap. This is because Old and OldMap represent the state of the record before the trigger fired. A newly inserted record has no prior database state and is therefore null. Instead, you should write your condition that considers if it's a before insert or before update. You might do this:

 

if(Trigger.old!=null && opp.StageName != Trigger.oldMap.get(opp.id).StageName))

Note that you don't need to check if StageName is null... it is a system-required field and will never be null.