Famous error: Conversion error when setting the value XXX to 'null Converter'

Asked

Viewed 2,243 times

3

Good afternoon.

I’m having the famous error "Conversion error when setting the value XXX to 'null Converter'." I’ve seen several topics here and in other forums, Showcase of the first faces and I couldn’t solve (in parts). In my application Have a user registration, inside it I have to save a Team (it’s like a third party company) by a Selectonemenu but when saving gives the famous error. Well I’ll put the codes:

Here is only the method of Dao listing the teams and Equipment:

@SuppressWarnings("unchecked")
    public List<Equipe> listar(){
        EntityManager manager = Persistence.createEntityManagerFactory("APRSAS").createEntityManager();
        javax.persistence.Query q =  (javax.persistence.Query) manager.createQuery("SELECT e FROM Equipe e");
        List<Equipe> equipes = ((javax.persistence.Query) q).getResultList();

        return equipes;
    }

Here the Bean of User:

@Entity
public class Usuario implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="userId", unique=true, nullable=false)
    private Integer userId;

    @Column(name="ativo")
    private boolean ativo;

    @Column(name="userNome")
    private String userNome;

    @Column(name="login")
    private String login;

    @Column(name="senha")
    private String senha;

    @Column(name="email")
    private String email;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    private Equipe equipe;  

    @Column(name="permissaoAcesso")
    private int permissaoAcesso;    

//get set .....
}

The class responsible for loading the list:

@ManagedBean(name="equipeService", eager = true)
@SessionScoped
public class EquipeService {

    private List<Equipe> equipes;
    EquipeDao equipedao = new EquipeDao();  

    public List<Equipe> getEquipes() {
            equipes = equipedao.listar();
        return equipes;
    }
}

After the mistake I discovered I had to create a convert, so I took this from showcase of Primefaces:

@FacesConverter("equipeConverter")
public class EquipeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if(value != null && value.trim().length() > 0) {
            try {
                EquipeService service = (EquipeService) fc.getExternalContext().getApplicationMap().get("equipeService");
                return service.getEquipes().get(Integer.parseInt(value));
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO AO CARREGAR EQUIPES", "Equipe não encontrada."));
            }
        }
        else {
            return null;
        }
    }

    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            return String.valueOf(((Equipe) object).getEquipeId());
        }
        else {
            return null;
        }
    }   
}

And the piece of xhtml who has the selectonemenu:

<p:outputPanel id="displayEquipe1">
                    <p:outputLabel value="Equipe:"
                        rendered="#{usuarioAddEditMB.usuario.permissaoAcesso == '3'}" />
                </p:outputPanel>
                <p:outputPanel id="displayEquipe2">
                    <p:selectOneMenu id="Equipe"
                        value="#{usuarioAddEditMB.usuario.equipe}"
                        converter="equipeConverter"
                        rendered="#{usuarioAddEditMB.usuario.permissaoAcesso == '3'}"
                        style="width:125px">
                        <f:selectItem itemLabel="Selecione" itemValue="#{null}" />
                        <f:selectItems value="#{equipeService.equipes}" var="equipe"
                            itemLabel="#{equipe.equipeNome}" itemValue="#{equipe}" />
                    </p:selectOneMenu>
                </p:outputPanel>

(Obs. ignore that rendered, it’s just a business rule)

After I created the Conveter no longer loaded the page and started appearing this error: java.lang.String cannot be cast to ... but on a topic in another forum I saw that I had to put a null in the itemValue, I did this and the page reloaded, but now when I order to save gives an error , but the console only appears written NULL, I don’t know but what to do to fix it.

Edited:

Please insert the error as it is printed in the log. To, for example, see which method is triggering the exception. @Luídne

I removed from the itemvalue the "#{null}" and left only the quotes, appeared this error:

Abr 09, 2017 5:36:13 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: java.lang.ClassCastException: java.lang.String cannot be cast to br.com.sistemaaprsas.bean.Equipe
    at br.com.sistemaaprsas.converter.EquipeConverter.getAsString(EquipeConverter.java:34)
    at org.primefaces.renderkit.InputRenderer.getOptionAsString(InputRenderer.java:164)
    at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeOption(SelectOneMenuRenderer.java:345)
    at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeSelectItems(SelectOneMenuRenderer.java:331)
    at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeInput(SelectOneMenuRenderer.java:114)
    at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeMarkup(SelectOneMenuRenderer.java:91)
    at org.primefaces.component.selectonemenu.SelectOneMenuRenderer.encodeEnd(SelectOneMenuRenderer.java:65)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:74)
    at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:57)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeMarkup(OutputPanelRenderer.java:64)
    at org.primefaces.component.outputpanel.OutputPanelRenderer.encodeEnd(OutputPanelRenderer.java:40)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1864)
    at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
    at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1690)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at javax.faces.component.UIForm.visitTree(UIForm.java:371)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at javax.faces.component.UIComponent.visitTree(UIComponent.java:1701)
    at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
    at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
    at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:57)
    at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1857)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:432)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at br.com.sistemaaprsas.filter.AuthFilter.doFilter(AuthFilter.java:39)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java

EDITED 2:

I have a search for ID in the DAO:

public Equipe getById(int equipeid) {
        EntityManager manager = Persistence.createEntityManagerFactory("APRSAS").createEntityManager();
        Equipe equipe = null;
        try{

            equipe =  manager.find(Equipe.class, equipeid);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return equipe;      
    }

I ended up changing my convert as searches, I arrived at this result:

@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
    if (value != null && value.trim().length() > 0) {
        try {
            return new EquipeDao().getById(Integer.parseInt(value));
        } catch (NumberFormatException e) {
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO AO CARREGAR EQUIPES",
                    "Equipe não encontrada."));
        }
    } else {
        return null;
    }
}

public String getAsString(FacesContext fc, UIComponent uic, Object object) {
    if (object != null && object instanceof Equipe) {
        return ((Equipe) object).getEquipeId().toString();
    }
    return null;

}

but now he’s throwing:

throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO AO CARREGAR EQUIPES",
                        "Equipe não encontrada."));
  • Please insert the error as it is printed in the log. For example, see which method is triggering the exception.

  • Okay, I’ll post it right away

  • So, as I said, in this code I posted the only error that looks on the console is null no more errors appear.

  • in itemvalue I took the value #{null} and left only the quotes appeared that mistake:

  • Print in log or in throw in getAsObject() the value of the parameter String value. To see why the exception.

  • Opa @Luídne I did out.printl of the value and it shows me the value of itemLabel and not itemValue, and I did the e.printStackTrace(); and also gives me the value of itemLabel

Show 1 more comment

1 answer

0


A friend handed me a convert that worked, worked perfect follows:

@FacesConverter("equipeConverter")
public class EquipeConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {

        if (value == null || value.equals(""))
            return null;
        try {
            Long id = Long.valueOf(value);
            Collection items = (Collection) uic.getAttributes().get("items");
            return findById(items, id);
        } catch (Exception ex) {
            throw new ConverterException("Não foi possível aplicar conversão de item com valor [" + value
                    + "] no componente [" + uic.getId() + "]", ex);
        }

        /*
         * if (value != null && value.trim().length() > 0) { try { return new
         * EquipeDao().getById(Integer.parseInt(value)); } catch
         * (NumberFormatException e) { throw new ConverterException(new
         * FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO AO CARREGAR EQUIPES",
         * "Equipe não encontrada.")); } } else { return null; }
         */
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null)
            return "";
        return getIdByReflection(value).toString();
    }

    private Object findById(Collection collection, Long idToFind) {
        for (Object obj : collection) {
            Long id = getIdByReflection(obj);
            if (id == idToFind)
                return obj;
        }
        return null;
    }

    private Long getIdByReflection(Object bean) {
        try {
            Field idField = bean.getClass().getDeclaredField("equipeId");
            idField.setAccessible(true);
            return (Long) Long.valueOf(idField.get(bean).toString());
        } catch (Exception ex) {
            throw new RuntimeException("Não foi possível obter a propriedade 'equipeId' do item", ex);
        }
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.