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
chubsubchubsub 

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

I'm getting this error message when referring to a variable in the query below:  The code works fine, but only throws this error message if there is a value in the SOF_Requested_Date field.  Whenever this is the case, nothing should happen, but if there is not any value in that field, another field is updated, which it does just fine.  

 

thanks for any advice!

 

list<Opportunity> allopps = [select Id, Daily_Tracking_Number__c, SOF_Requested_Date__c, AccountId, CreatedDate
from Opportunity
where AccountId in :accids
and (CreatedDate > :FirstDate.addDays(-1))  //This is the line that is causeing the error
and (CreatedDate < :LastDate.addDays(1))
order by AccountId, CreatedDate];

Best Answer chosen by Admin (Salesforce Developers) 
lakslaks

Hi,

 

Looks like the variable FirstDate is null in the line indicated.

Since the code previous to the query has not been included here, I assume that the variable FirstDate has not been assigned the required value at some point before the query.

In that case invoking the function addDays() on the variable will cause NullPointerException to be thrown.

 

So make sure your Date variable is assigned the required value before invoking a function on it.

 

For eg:

This will work fine:

Date dt = Date.newInstance(2011, 11, 23);
Date newdate = dt.addDays(1);

 

where as this will throw NullPointer:

Date dt;
Date newdate = dt.addDays(1);

 

Hope this solves your problem. If so please mark it as solution so that others may benefit. If not do let me know what went wrong.

 

Regards,

Lakshmi.