The JSF AutoComplete component does not work

1

IhaveanapplicationthatmustenterSocialReason,CNPJandcity,boththeSocialReasonandCPNJfieldsareworkingnormally,howeverthefieldthathastoenterthecityisgivingthiserror.

Ago26,20141:23:30PMorg.apache.catalina.core.AprLifecycleListenerinitINFORMAÇÕES:TheAPRbasedApacheTomcatNativelibrarywhichallowsoptimalperformanceinproductionenvironmentswasnotfoundonthejava.library.path:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/libAgo26,20141:23:30PMorg.apache.tomcat.util.digester.SetPropertiesRulebeginADVERTÊNCIA:[SetPropertiesRule]{Server/Service/Engine/Host/Context}Settingproperty'source'to'org.eclipse.jst.jee.server:CadastroContratos'didnotfindamatchingproperty.Ago26,20141:23:30PMorg.apache.coyote.AbstractProtocolinitINFORMAÇÕES:InitializingProtocolHandler["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

From the knowledge acquired by typing "Re" in the Contract City field, it should show in a little bubble the possible words in our code if it is Recife. it would be more or less like this

IjusttypedinthisfieldbecauseIamabsolutelysurethattheproblemisinthealgorithmthatislinkedtotheContractCityfield.

Justknowwheretheerroris,yesterdayItriedalotallday,Icanonlyaskforhelp,doyouhaveanysuggestions?

hereisthecode

importjava.io.Serializable;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;importjavax.faces.application.FacesMessage;importjavax.faces.bean.ManagedBean;importjavax.faces.bean.ViewScoped;importjavax.faces.context.FacesContext;@ManagedBean@ViewScopedpublicclassCadastroContratoBeanimplementsSerializable{privatestaticfinallongserialVersionUID=1L;privateList<String>cidades=newArrayList<String>();privateStringrazaoS;privateStringcnpj;privateStringcidades_do_Contrato;publicCadastroContratoBean(){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 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>

I tried to debug

this is the result

I think it's a null pointer, and I do not know how to get the error.

    
asked by anonymous 26.08.2014 / 18:31

1 answer

3

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

And besides, it was returning an empty%% and not the cities that satisfy its 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;
}
    
26.08.2014 / 18:48