I'm building a method to update two date fields when a different date field is edited. When I update one of the date fields or both of the fields the error in the debug log is "Attempt to de-reference a null object".
My method looks like this:
private void updateRenewalDates(Map<Id, OpportunityLineItem> newMap, Map<Id, OpportunityLineItem> oldMap)
{
// Create Lists to hold data
List<OpportunityLineItem> renewals = new List<OpportunityLineItem>();
Map<Id,List<OpportunityLineItem>> oppToLineItem = new Map<Id,List<OpportunityLineItem>>();
// Loop through filter records from the api call and see if they meet the criteria
System.debug('list of renewals is: ' + renewals); // Should be blank
System.debug('Map of oppToLineItem is ' + oppToLineItem); // Should be blank
System.debug('newMap is ' + newMap); // Should have a value
System.debug('oldMap is ' + oldMap); // Should have a vlaue
for(OpportunityLineItem oli:newMap.values())
{
if((oli.Start_Date__c != oldMap.get(oli.id).Start_Date__c) || (oli.End_Date__c != oldMap.get(oli.id).End_Date__c))
{
System.debug('Map of oppToLineItem is ' + oppToLineItem); // Should be blank
oppToLineItem.get(oli.Id).add(oli);
System.debug('Map of oppToLineItem is ' + oppToLineItem); // Should not blank
}
}
// Get the record fields for records where the id is from our list
renewals = [SELECT Id, Start_Date__c, Start_Date_Renewal__c, End_Date__c, End_Date_Renewal__c, Opportunity.ContractTerm__c
FROM OpportunityLineItem
WHERE Id in:oppToLineItem.keyset()];
// Loop through results of the query and update the record with the new value
for(OpportunityLineItem oppLineItem:renewals)
{
List<OpportunityLineItem> olis = oppToLineItem.get(oppLineItem.OpportunityId);
for(OpportunityLineItem line:olis)
{
// Update Renewal dates with the start/end date + Contract length
line.Start_Date_Renewal__c = line.Start_Date__c.addMonths(Integer.valueOf(line.Opportunity.ContractTerm__c));
line.End_Date_Renewal__c = line.End_Date__c.addMonths(Integer.valueOf(line.Opportunity.ContractTerm__c));
}
}
}
More specifically I think the error is in this chunk:
for(OpportunityLineItem oli:newMap.values())
{
if((oli.Start_Date__c != oldMap.get(oli.id).Start_Date__c) || (oli.End_Date__c != oldMap.get(oli.id).End_Date__c))
{
System.debug('Map of oppToLineItem is ' + oppToLineItem); // Should be blank
oppToLineItem.get(oli.Id).add(oli);
System.debug('Map of oppToLineItem is ' + oppToLineItem); // Should not blank
}
}
In my debug log it shows that the map oppToLineItem is null, hence the de-reference a null object. However, I can also see the newMap and oldMap and the value is different as I expect in my criteria. How come then the record does not get added to the Map if it does meet the criteria?