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
uxtx_timuxtx_tim 

add item to list throws null pointer exception

I am attempting to add items to a list and update the page to show the items in the list.  To start off with the list is empty.  The idea is to enter text into the inputText box and it gets added to the list, the command button refreshes the apex:repeat element and displays what was just entered.  Instead, when I click the action button, I get a system null pointer exception error - attempt to de-reference a null object.

 

Heres the visualforce

 

 

                <apex:repeat id="List" value="{!testStringList}" var="str">
                   <apex:outputText >{!str}</apex:outputText>
                </apex:repeat>
                    <apex:pageBlock id="NewListItem">                                           
                            <apex:inputText value="{!testString}"/>
                    </apex:pageBlock>
                
               <apex:commandButton action="{!addToTestStringList}" styleClass="formButton" value="+ Add Year" rerender="List"/> 

 

 

 

Here is the apex controller:

 

  public List<String> testStringList {get;set;}
    
  public String testString {get; set;}
       
  public PageReference addToTestStringList(){   
      testStringList.add(testString);   
      return null;
    }

 

Furthermore, how can I initialize my list with one empty string?

Best Answer chosen by Admin (Salesforce Developers) 
aballardaballard

You haven't created  the list.  Somewhere, probably in a constructor, you need a

  testStringList = new List<String>();

 

You can add an empty string at the same time. 

All Answers

aballardaballard

You haven't created  the list.  Somewhere, probably in a constructor, you need a

  testStringList = new List<String>();

 

You can add an empty string at the same time. 

This was selected as the best answer
uxtx_timuxtx_tim

D-oh!

 

Thanks!