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=" {!Attachment.name}" 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).

  • If attachment is null, attachment.body will throw a NullPointerException. Check if (attachment!=null && attachment.body!=null) – techtrekker Nov 30 '12 at 8:24

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" />
  • i don't know why this error is not getting fixed. I have also tried a lot of time but . – AnuRaj Nov 30 '12 at 6:19
  • Try this! Replace the code "if( attachment.body != null) " as "if( attachment!= null && attachment.body != null) " – Priyanka Nov 30 '12 at 9:10
  • ya i did it but the get set method is not get invoked. Do you have any luck? – AnuRaj Nov 30 '12 at 9:30

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;

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.