The JSF Autocomplete component does not work

Asked

Viewed 1,415 times

1

inserir a descrição da imagem aqui

I am with an application that should enter Social Reason, CNPJ and the city, the two fields Social Reason and CPNJ are working normally, however the field that has to type the city is giving this error.

Ago 26, 2014 1:23:30 PM org.apache.catalina.core.AprLifecycleListener init
INFORMAÇÕES: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Ago 26, 2014 1:23:30 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
ADVERTÊNCIA: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:CadastroContratos' did not find a matching property.
Ago 26, 2014 1:23:30 PM org.apache.coyote.AbstractProtocol init
INFORMAÇÕES: Initializing ProtocolHandler ["http-bio-8080"]
Ago 26, 2014 1:23:30 PM org.apache.coyote.AbstractProtocol init
INFORMAÇÕES: Initializing ProtocolHandler ["ajp-bio-8009"]
Ago 26, 2014 1:23:30 PM org.apache.catalina.startup.Catalina load
INFORMAÇÕES: Initialization processed in 580 ms
Ago 26, 2014 1:23:30 PM org.apache.catalina.core.StandardService startInternal
INFORMAÇÕES: Starting service Catalina
Ago 26, 2014 1:23:30 PM org.apache.catalina.core.StandardEngine startInternal
INFORMAÇÕES: Starting Servlet Engine: Apache Tomcat/7.0.55
Ago 26, 2014 1:23:32 PM com.sun.faces.config.ConfigureListener contextInitialized
INFORMAÇÕES: Inicializando Mojarra 2.1.17 ( 20130107-1935 https://svn.java.net/svn/mojarra~svn/tags/2.1.17@11335) para o contexto '/CadastroContratos'
Ago 26, 2014 1:23:32 PM com.sun.faces.spi.InjectionProviderFactory createInstance
INFORMAÇÕES: JSF1048: Anotações PostConstruct/PreDestroy presentes.  Os métodos ManagedBeans marcados com essas anotações informarão as anotações processadas.
Ago 26, 2014 1:23:32 PM org.primefaces.webapp.PostConstructApplicationEventListener processEvent
INFORMAÇÕES: Running on PrimeFaces 3.5
Ago 26, 2014 1:23:32 PM com.sun.faces.config.ConfigureListener$WebConfigResourceMonitor$Monitor <init>
INFORMAÇÕES: Monitoring jndi:/localhost/CadastroContratos/WEB-INF/faces-config.xml for modifications
Ago 26, 2014 1:23:33 PM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["http-bio-8080"]
Ago 26, 2014 1:23:33 PM org.apache.coyote.AbstractProtocol start
INFORMAÇÕES: Starting ProtocolHandler ["ajp-bio-8009"]
Ago 26, 2014 1:23:33 PM org.apache.catalina.startup.Catalina start
INFORMAÇÕES: Server startup in 2442 ms
Ago 26, 2014 1:23:43 PM com.sun.faces.lifecycle.ApplyRequestValuesPhase execute
ADVERTÊNCIA: /Cadastro.xhtml @28,63 completeMethod="#{cadastroContratoBean.sugerirCidades}": java.lang.NullPointerException
javax.el.ELException: /Cadastro.xhtml @28,63 completeMethod="#{cadastroContratoBean.sugerirCidades}": java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:359)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:795)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:936)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    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:745)
Caused by: java.lang.NullPointerException
    at com.algaworks.exercicio1.CadastroContratoBean.sugerirCidades(CadastroContratoBean.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 27 more

by the knowledge acquired by typing "Re" in the field Contract City it must show in a balloon the possible existing words in our code if it is Recife. would be more or less like this

inserir a descrição da imagem aqui

I only typed in this field because I am absolutely sure that the problem is in the algorithm that is linked to the Contract City field.

just knowing where the mistake is, yesterday I tried hard all day, only I can ask for help, have any suggestions?

here is the code

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@ViewScoped
public class CadastroContratoBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<String> cidades = new ArrayList<String>();
    private String razaoS;
    private String cnpj;
    private String cidades_do_Contrato;

    public CadastroContratoBean() {
        cidades.add("Recife");
        cidades.add("Tocantes");
        cidades.add("São Paulo");
        cidades.add("Minas Gerais");
        cidades.add("Curitiba");
        cidades.add("Porto Alegre");
        cidades.add("Belo Horizonte");

    }

    public List<String> sugerirCidades(String consulta) {
        List<String> cidadesSugeridas = new ArrayList<String>();

        for (String indiceCidades : this.cidades) {
            if (cidades_do_Contrato.toLowerCase().startsWith(
                    consulta.toLowerCase())) {
                cidadesSugeridas.add(indiceCidades);
            }

        }

        return new ArrayList<String>();

    }

    public void Cadastrar() {
        System.out.println("Nome: " + this.razaoS);
        System.out.println("CNPJ: " + this.cnpj);
        System.out.println("Cidade do Contrato: " + this.cidades_do_Contrato);

        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage("Cadastro efetuado com Sucesso"));

    }

    public String getRazaoS() {
        return razaoS;
    }

    public void setRazaoS(String razaoS) {
        this.razaoS = razaoS;
    }

    public String getCnpj() {
        return cnpj;
    }

    public void setCnpj(String cnpj) {
        this.cnpj = cnpj;
    }

    public String getCidades_do_Contrato() {
        return cidades_do_Contrato;
    }

    public void setCidades_do_Contrato(String cidades_do_Contrato) {
        this.cidades_do_Contrato = cidades_do_Contrato;
    }

}

this one is xhtml

 xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://java.sun.com/jsf/core">
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:body>

    <h:form id="frm">
        <p:messages autoUpdate="true" />
        <f:facet name="header">
    Cadastro de Contratos Algaworks
    </f:facet>

        <p:panelGrid columns="2">
            <p:outputLabel value="Razao Social" for="razao" />
            <p:inputText id="razao" value="#{cadastroContratoBean.razaoS}"
                required="true" />
            <p:outputLabel value="CNPJ" for="cnpj" />
            <p:inputMask id="cnpj" mask="99.999.999/9999-99" maxlength="20"
                value="#{cadastroContratoBean.cnpj}" />
            <p:outputLabel value="Cidade do Contrato" for="cidade" />
            <p:autoComplete id="cidade"
                value="#{cadastroContratoBean.cidades_do_Contrato}" required="true"
                completeMethod="#{cadastroContratoBean.sugerirCidades}" />

        </p:panelGrid>

        <p:commandButton value="Cadastrar"
            action="#{cadastroContratoBean.Cadastrar}" />

    </h:form>
</h:body>
</html>

tried to thresh

that is the result

inserir a descrição da imagem aqui

I believe it is a null pointer, and I do not know how to remove the error.

1 answer

3


The problem with your code is that you are using the attribute cidades_do_Contrato (completion of the autocomplete) and not the indiceCidades created by foreach, as a comparator during the iteration of cities, to which at the moment it is null.

And in addition was returning a ArrayList empty and not the cities that satisfy your filter.

Try switching to:

public List<String> sugerirCidades(String consulta) {
    List<String> cidadesSugeridas = new ArrayList<String>();

    for (String indiceCidades : this.cidades) {
        if (indiceCidades.toLowerCase().startsWith(consulta.toLowerCase())) {
            cidadesSugeridas.add(indiceCidades);
        }
    }

    return cidadesSugeridas;
}
  • it worked out really well. I am very grateful.

  • Wow, the guy hit his eye and already caught the mistake. WOW

  • @wladyband, it is normal to sometimes pass an error like this, either by tiredness or time, and just to show the code to another already helps to solve the problem.

Browser other questions tagged

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