kanika
kanika

Reputation: 1

Adding values in List<String> dynamically

Every time a new String is generated but the List is having null value for it.

<h:dataTable value="#{add.periods}" var="prd">
        <h:column><h:inputText value="#{prd}"  /></h:column>
    </h:dataTable>
    <h:commandButton value="add" action="#{add.addList}" />
    <h:commandButton value="submit" action="#{add.submit}" />
</h:dataTable>    

Entity AddPeriods: object add

private List<String> periods = new ArrayList<String>();
    @ElementCollection
     public List<String> getPeriods() 
     {         
            return periods;
     }
        public void setPeriods(List<String> periods)      
        {

         this.periods=periods;
         }

         public void addList() 
         { 

          periods.add(new String());

         }
          public void submit()
          {
          System.out.println("periods..................................: " +periods);
           }

Message on Console:After 2 times addition

    periods..................................: [, ]

Upvotes: 0

Views: 4394

Answers (3)

Logan
Logan

Reputation: 2505

Pass some String to the function addList, else it will keep on adding empty Strings to the list. When you write something like, periods.add(new String("Kanika")), and its added in List as many times as you press add button, that means your function is working fine. But unless and until you will pass something to it, it will not insert anything meaningful.

Upvotes: 1

Andreas Johansson
Andreas Johansson

Reputation: 1145

You just add a new empty string. Switch it to something else, e.g:

periods.add(new String("hey there!"));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500525

It's not adding a null value (it's not a null reference) - but it's not adding a useful value:

periods.add(new String());

In what way were you expecting that to be useful? Shouldn't you be adding a useful string value instead of just a new empty string?

Upvotes: 3

Related Questions