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
S@uravvS@uravv 

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

When I try to Query 
Invoice__C[] InvoiceData =  [Select Id,Attachment_Id__c,Supporting_Attachment_Id__c from Invoice__c where Id=:InvoiceId]; 
In the debug I see Only Id and Attachment_Id__c fields, because Supporting_Attachment_Id__c is null.
But then I try to  check it using below line.
if(InvoiceData[0].Supporting_Attachment_Id__c == ''||InvoiceData[0].Supporting_Attachment_Id__c == null)
It throws System.NullPointerException: Attempt to de-reference a null object.

How to solve this issue?
Ashvin JAshvin J
Hello S@uravv , 

Please debug the 'InvoiceData[0]' as well. See if it is printing NULL ?

Probably your query is not returning a record. 

Thanks,
Ashvin
Danish HodaDanish Hoda

hi Saurav,
try

if(!String.isBlank(InvoiceData[0].Supporting_Attachment_Id__c)) {
   //your condition if there is a value
}

S@uravvS@uravv
Hello Ashvin,

System.debug doesn't print fileds with null value. Hence I am getting only Id and Attachment_Id__c in my debug.
ravi soniravi soni
Hi S@uravv,
try following way.
for(Invoice__C InvoiceData : [Select Id,Attachment_Id__c,Supporting_Attachment_Id__c FROM Invoice__c 
                              where Id=:InvoiceId]){
if(InvoiceData.Supporting_Attachment_Id__c == ''|| InvoiceData.Supporting_Attachment_Id__c == null){
//Write your code here
}
}
let me know if it helps you and marking it as best.
Thank you
 
S@uravvS@uravv
Hi Danish,

It gave me the same error with your solution.
S@uravvS@uravv
I could solve the problem by using !String.isNotEmpty.
But I ran into a similar issue in which the insert operation is not letting me access the id of the inserted record.
It throws a null pointer exception. Though the record is getting inserted, I checked on Workbench.

                        insert supportAttachment;
                        system.debug('Attachment Inserted');
                        supportingAttachmentId = supportAttachment.id; 
Ashvin JAshvin J
Hi S@uravv, 

Did you check if it is returning any exception or validation error which is preventing the insert supportAttachment operation ? Are you using try catch block ?

Also add the debug for supportAttachment after insert dml. Check if it is displaying the ID field, in this case it will not but just have a look. 

Thanks.
Ashvin