Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: java.util.ArrayList cannot be cast to javax.faces.model.SelectItem [duplicate]

Tags:

jsf-2

I am trying to make my dropdown dynamic and below is the code and exception i am getting. Please help me out

bean:

    private String dropDownValue;
    List<SelectItem> testDropDown = new ArrayList<SelectItem>();
    List<SelectItem> testDropDownTwo = new ArrayList<SelectItem>();

    public String getDropDownValue() {
        return dropDownValue;
    }


    public void setDropDownValue(String dropDownValue) {
        this.dropDownValue = dropDownValue;
    }


    public List<SelectItem> getTestDropDown() {
        testDropDown.add(new SelectItem("One"));
        testDropDown.add(new SelectItem("Two"));
        testDropDown.add(new SelectItem("Three"));
        testDropDown.add(new SelectItem("Four"));
        return testDropDown;
    }

XHtml Code:

<h:selectOneMenu value="#{loginBean.dropDownValue}">
    <f:selectItem value="#{loginBean.testDropDown}" />
</h:selectOneMenu>

Exception:

exception

    javax.servlet.ServletException: java.util.ArrayList cannot be cast to javax.faces.model.SelectItem
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)

    root cause 
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to javax.faces.model.SelectItem
    com.sun.faces.renderkit.SelectItemsIterator.initializeItems(SelectItemsIterator.java:185)               com.sun.faces.renderkit.SelectItemsIterator.hasNext(SelectItemsIterator.java:131)
    com.sun.faces.renderkit.html_basic.MenuRenderer.renderOptions(MenuRenderer.java:758)
    com.sun.faces.renderkit.html_basic.MenuRenderer.renderSelect(MenuRenderer.java:840)
    com.sun.faces.renderkit.html_basic.MenuRenderer.encodeEnd(MenuRenderer.java:294)
    javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:879)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)

Some classcast exception is happening. but i am sending the ArrayList of SelectItem to the list

if i change the Value attribute in selectItem tag to itemValue it is not trowing a exception but i am not getting any value i am getting the object names as in the drop down in a single list

like image 554
user2727493 Avatar asked Dec 09 '22 10:12

user2727493


1 Answers

You have to use f:selectItems:

<h:selectOneMenu value="#{loginBean.dropDownValue}">
    <f:selectItems value="#{loginBean.testDropDown}"/>
</h:selectOneMenu>

f:selectItem is used to add a single SelectItem to the menu, to add a whole List of SelectItems you have to use this tag.

like image 126
user1983983 Avatar answered May 12 '23 03:05

user1983983