+ Start a Discussion

Apex Trigger Help System.NullPointerException: Attempt to de-reference a null object

The following class is referenced in a trigger on the Quote.  I am trying to populate a field on the Quote called Tracking Number.  This tracking number will contain a number sequence to keep track of how many quotes have been created on an opportunity.  So, if the first Quote is created, the Tracking_Number__c will equal to 1, then, the second Quote is created, the number wil be 2.  I'm getting the System.NullPointerException: Attempt to de-reference a null object error message on the highlighted line.  Any ideas on how to fix it?


Thanks in advance for any suggestions. 



public static list<Quote> beforeInsert(list<Quote> quos) {
set<Id> oppids = new set<id>();
map<Id, Quote> oppid2quotemap = new map<Id, Quote>();

for (Quote q : quos)
oppid2quotemap.put(q.Opportunity.Id, q);

//query for Opps with Quotes attached
list<Opportunity> oppswquotes = [select Id, Name,
(select Id, Tracking_Number__c from Quotes order by CreatedDate)
from Opportunity
where Id in :oppids];

for (Opportunity o : oppswquotes)
Integer counter = 1;
for (Quote q : o.Quotes)

q.Tracking_Number__c = counter;

if (Trigger.newmap.containsKey(q.Id))
Quote thisquote = (Quote)Trigger.newmap.get(q.Id);
thisquote.Tracking_Number__c = counter;
counter ++;

//if IsInsert, use counter to set triggering Quote
//find triggering Quote from a map<Id, Quote>: Opportunity ID 2 Quote map

Quote thisquote = oppid2quotemap.get(o.Id);
thisquote.Tracking_Number__c = counter;

//this will include the quotes we need to count

list<Quote> allquos = [select Id, OpportunityId, CreatedDate
from Quote
where OpportunityId in :oppids
order by OpportunityId, CreatedDate];

map<Id, Integer> quoid2seqnummap = new map<Id, Integer>();

//now go back through passed Quote list

for (Quote q :quos)
Integer seqnum = quoid2seqnummap.get(q.Id);
//TODO: populate Name field or store seq num somewhere

q.Tracking_Number__c = seqnum;

return quos;



Before insert Id will be null. Check if you can use after insert or use another field or fields to identify the record.