I have below code to allow multiple file attachments to be inserted against a parent record id. But this results in either View state size limit exceeded (not all the time) or dereferencing null object at below line(when using transient to by pass view state). Can someone please help me here?

Code snippet:

public Pagereference SaveAttachments()  
        String callId='a04L0000003SQZV';//remove later
        //String callId = System.currentPagereference().getParameters().get('id');  
        if(callId == null || callId == '')  
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'No record is associated. Please pass record Id in parameter.'));  
        if(Counting== null )  
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select how many files you want to upload.'));  

        transient List<Attachment> listToInsert = new List<Attachment>() ;  

        //Attachment a = new Attachment(parentId = callId, name=myfile.name, body = myfile.body);  
        for(Attachment a: allFileList)  // Null Pointer error
            if(a.name != '' && a.name != '' && a.body != null)  
                listToInsert.add(new Attachment(parentId = callId, name = a.name, body = a.body)) ;  

        //Inserting attachments  
        if(listToInsert.size() > 0)  

            insert listToInsert ;  

            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.INFO, listToInsert.size() + ' file(s) are uploaded successfully'));  
            Counting= 0 ;  
            ApexPages.addmessage(new ApexPages.message(ApexPages.Severity.ERROR,'Please select at-least one file'));  

        return null;  

    public PageReference ChangeCount()  
        allFileList.clear() ;  //  Error with de-reference null object
        Counting=Counting+1;  //
        //Adding multiple attachments instance  
        for(Integer i = 1 ; i <= Counting; i++)  //Integer.valueOf(FileCount) 
            allFileList.add(new Attachment()) ;  
        return null ;  

1 Answer 1


Instead of using allFileList.clear() ; try

allFileList = new List<Attachment>();

when using transient that variable will become null as soon as the method terminates. So you can not call any method on null object.

  • Now I am getting below error at mentioned line. Error: NullPointerException: Attempt to de-reference a null object Mar 30, 2015 at 13:18
  • @SFDC_GEEK when using transient keywork you can not maintain state of that variable. So if you call another action the transient variable will become null.
    – Ashwani
    Mar 30, 2015 at 13:22
  • 1
    Can you please let me know how to get it resolved? Mar 31, 2015 at 9:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .