Good afternoon.
I am with the famous error "Conversion error when setting XXX value to 'null Converter'." I have already seen several topics here and in other forums, Showcase of primefaces and I could not solve (in parts). In my application It has a user registry, inside it I have to save a Team (it's like a company outsourced) by a SelectOneMenu but at the time of saving gives the famous error. Well I'll put the codes:
Here's just the Dao method that lists teams and TeamDao:
@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 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 error I discovered that I had to create a convert , then I took this one from the Primefaces showcase :
@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 that has 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>
(ignore that rendered, it's just a business rule)
After I created the conveter I did not load the page anymore and this error started: java.lang.String can not be cast to ... but in a topic in another forum I saw that I had to put a null in the itemValue
, I did that and the page reloaded, so now when I give save it gives an error, strong> NULL , I do not know what to do to fix this.
Edited:
Please put the error as it is printed in the log. For, for example, see which method is firing the exception. @ Luigi
I took the itemvalue "# {null}" and left only the quotation marks, this error appeared:
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
EDIT 2:
I have a search for ID in 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 converter according to searches, I came up with 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 it goes into throw:
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRO AO CARREGAR EQUIPES",
"Equipe não encontrada."));