Find your content:

Search form

You are here

Attempt to de-reference a null object with Attachment


I am trying to add a attachment to a record. Their may or may not be attachment. So that i have created a attachment in the controller if the attachment is null but i am getting null point exception. EXCEPTION_THROWN|[74]|System.NullPointerException: Attempt to de-reference a null object

my code

<apex:form > 
 <apex:pageBlock >
   <apex:pageBlockSection columns="6" >
      <apex:pageBlockSectionItem >
        <apex:outputLabel value="" for="fileInput" />
         <apex:inputFile value="{!Attachment.body}" id="fileInput" filename=" {!}" dir="RTL" accept=".xlsx,.pdf,.docx" size="50" />

    public Attachment attachment;
 public Attachment getAttachment() 
     system.debug('Result : In attachment get () ');
     if(attachment == null) 
             attachment = new Attachment();
     return attachment;
 if(exp.Receipt_Attached__c == true && attachment.body == null)
             ApexPages.Message attMsg = new  ApexPages.Message(ApexPages.severity.ERROR,'Expense Receipt is Required.'); 
            return null;
         system.debug('Result : attachment '+ attachment); 
         if( attachment.body != null) 

I am getting error on this line of code if( attachment.body != null).

Attribution to: AnuRaj

Possible Suggestion/Solution #1

Instead of binding the value in the page as 'value="{!Attachment.body}"', create a blob variable in the controller named "AttachmentBody" and bind the blob value to the page as shown below. And assign the blob value to the attachment.body if the blob is not equal to null.


Public blob AttachmentBody {get;set;} // For binding to page
public Attachment att 
        if (att == null) att = new Attachment();
        return att;
att.body = AttachmentBody; 


<apex:inputFile id="addFile" accept="doc,docx,pdf,xls,xlsx,ppt,pptx" value="{!AttachmentBody}" title="Upload Word, Excel, PDF or PowerPoint" filename="{!AttachmentFilename}"  styleClass="forIpText docListStyle3 TextPriority7" />

Attribution to: Priyanka

Possible Suggestion/Solution #2

Thanks, I have solved it. It was issue of the declaration of apex:form. The button i declared was in the another form.

Attribution to: AnuRaj

Possible Suggestion/Solution #3

When you create a new Attachment, set the body attribute to a non-null value initially:

if(attachment == null) {
    attachment = new Attachment();
    attachment.body = Blob.valueOf('');
return attachment;

Attribution to: Jeremy Nottingham
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content