NullPointerException SelectOneMenu [JSF + PRIMEFACES]

0

In a JSF page about a car shop, first select the car brand and then choose the model. However, when selecting an item from the first menu "Hyundai", it gives NullPointerException and I can not understand. I've tried a lot, I'm a beginner in JSF.

  

UPDATED (JA NO MANEGED BEAN COMING NULL).   After you leave the method   Query () of the DAO the selectedSelected is already null, in the case when   I selected the other menu was to get the value related to the   first menu "Selected brand" (Hyundai) and see which models   available showing in menu2.

View:

 <h:form id="frmVendas">
    <p:outputPanel id="venderCarro" />
    <h:panelGrid id="painel" columns="1">

        <p:outputLabel for="comboMarca" value="Marcas*: " />
        <p:selectOneMenu id="comboMarca" converter="conversorObjetoId" value="#{vendasMB.marcaSelecionada}">
            <f:selectItem itemLabel="--Selecione--" itemValue="" />
            <f:selectItems value="#{vendasMB.listaMarca}" var="marca" itemLabel="#{marca.nome}" itemValue="#{marca}" />
            <p:ajax event="change" update="comboModelos" listener="#{vendasMB.carregarModelos}" />
        </p:selectOneMenu>
    </h:panelGrid>

    <h:panelGrid id="painel2" columns="1">
        <p:outputLabel for="comboModelos" value="Modelos*: " />
        <p:selectOneMenu id="comboModelos" value="#{vendasMB.modeloSelecionado}" converter="conversorObjetoId">
            <f:selectItem itemLabel="--Selecione--" itemValue="" />
            <f:selectItems value="#{vendasMB.listaModelo}" var="carro" itemLabel="#{carro.modelo}" itemValue="#{carro}" />
        </p:selectOneMenu>
    </h:panelGrid>
 </h:form>

Managed bean

Two methods for SelectOneMenu

private List<Carro> listaCarros = new ArrayList<Carro>();
private List<Marca> listaMarca = new ArrayList<Marca>();
private List<Carro> listaModelo = new ArrayList<Carro>();
private String carroSelecionado;
private Marca marcaSelecionada ;
private Carro modeloSelecionado;

@PostConstruct
public void init() {
    listaMarca = carrosDAO.consultarMarca();
    System.out.println("--> init*()");
}
public void carregarModelos() {
    listaModelo = carrosDAO.consultarModelos(marcaSelecionada);
    //return listaModelo;
}

DAO:

public List<Marca> consultarMarca() {
        List<Marca> listaMarca = new ArrayList<Marca>();
        StringBuilder sb = new StringBuilder();
        Marca marca;
        Integer idMarca = 0;
        try {
            Connection con;
            Statement stmt = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            String urloracle = "jdbc:oracle:thin:@172.30.0.25:1521:desv";
            String useroracle = "rodrigoscs";
            String passwordoracle = "regueiro";

            OracleDataSource ds;
            ds = new OracleDataSource();
            ds.setURL(urloracle);
            con = ds.getConnection(useroracle, passwordoracle);
            stmt = con.createStatement();


                sb.append("SELECT NOME, ID FROM MARCA ");


            ps = con.prepareStatement(sb.toString());
            rs = ps.executeQuery();

            // percorre o resultado da consulta
            while (rs.next()) {

                marca = new Marca();

                marca.setMarcaID(++idMarca);
                marca.setNome(rs.getString("NOME"));
                marca.setMarcaID(rs.getInt("ID"));
                listaMarca.add(marca);

            }

            // fechando a connection
            if (con != null) {
                con.close();
                con = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }

            if (rs != null) {
                rs.close();
                rs = null;
            }

        } catch (SQLException ex) {
            System.out.println("Erro: " + ex.getMessage());
        }
        return listaMarca;
    }

Method giving NullPointerException :

public List<Carro> consultarModelos(Marca marcaSelecionada) {
        List<Carro> listaModelo = new ArrayList<Carro>();
        StringBuilder sb = new StringBuilder();
        Carro carro;
        Integer idCarro = 0;
        try {
            Connection con;
            Statement stmt = null;
            PreparedStatement ps = null;
            ResultSet rs = null;
            String urloracle = "jdbc:oracle:thin:@172.30.0.25:1521:desv";
            String useroracle = "rodrigoscs";
            String passwordoracle = "regueiro";

            OracleDataSource ds;
            ds = new OracleDataSource();
            ds.setURL(urloracle);
            con = ds.getConnection(useroracle, passwordoracle);
            stmt = con.createStatement();

            sb.append("SELECT C.CARROS_MODELO, M.NOME FROM CARROS C, MARCA M WHERE ID = CARROS_ID AND M.ID= ? ");

            ps = con.prepareStatement(sb.toString());
            ps.setInt(1, marcaSelecionada.getMarcaID());

            rs = ps.executeQuery();

            // percorre o resultado da consulta
            while (rs.next()) {

                carro = new Carro();
                carro.setId(++idCarro);
                carro.setModelo(rs.getString("CARROS_MODELO"));
                listaModelo.add(carro);

            }

            // fechando a connection
            if (con != null) {
                con.close();
                con = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }

            if (rs != null) {
                rs.close();
                rs = null;
            }

        } catch (SQLException ex) {
            System.out.println("Erro: " + ex.getMessage());
        }
        return listaModelo;
    }

get and set

    public List<Marca> getLista() {
        return listaMarca;
    }

    public void setLista(List<Marca> lista) {
        this.listaMarca = lista;
    }

    public List<Marca> getListaMarca() {
        return listaMarca;
    }

    public void setListaMarca(List<Marca> listaMarca) {
        this.listaMarca = listaMarca;
    }

    public Marca getMarcaSelecionada() {
        return marcaSelecionada;
    }

    public void setMarcaSelecionada(Marca marcaSelecionada) {
        this.marcaSelecionada = marcaSelecionada;
    }

    public List<Carro> getListaModelo() {
        return listaModelo;
    }

    public void setListaModelo(List<Carro> listaModelo) {
        this.listaModelo = listaModelo;
    }

    public Carro getModeloSelecionado() {
        return modeloSelecionado;
    }

    public void setModeloSelecionado(Carro modeloSelecionado) {
        this.modeloSelecionado = modeloSelecionado;
    }
}

ERROR:

- > init * ()

Jan 11, 2017 9:00:46 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
Advertência: /telaDeVendas.xhtml @21,107 listener="#{vendasMB.carregarModelos}": java.lang.NullPointerException
javax.el.ELException: /telaDeVendas.xhtml @21,107 listener="#{vendasMB.carregarModelos}": java.lang.NullPointerException
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:53)
    at javax.faces.event.AjaxBehaviorEvent.processListener(AjaxBehaviorEvent.java:113)
    at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:106)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:762)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    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:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at DAO.CarrosDAO.consultarModelos(CarrosDAO.java:168)
    at MB.VendasMB.carregarModelos(VendasMB.java:82)
    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:274)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 29 more

Jan 11, 2017 9:00:46 AM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
Grave: java.lang.NullPointerException
    at DAO.CarrosDAO.consultarModelos(CarrosDAO.java:168)
    at MB.VendasMB.carregarModelos(VendasMB.java:82)
    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:274)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at org.primefaces.component.behavior.ajax.AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxBehaviorListenerImpl.java:53)
    at javax.faces.event.AjaxBehaviorEvent.processListener(AjaxBehaviorEvent.java:113)
    at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:106)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:762)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    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:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
    
asked by anonymous 10.01.2017 / 16:51

1 answer

0

Dude, I've remapped your entire DAO:

public class CarrosDAO() {

    private static final URL_DB = "jdbc:oracle:thin:@172.30.0.25:1521:desv";
    private static final USUARIO = "rodrigoscs";
    private static final SENHA = "regueiro";

    private final OracleDataSource ds;

    public CarrosDAO() {
        try {
            ds = new OracleDataSource();
            ds.setURL(URL_DB);
            ds.setUser(URL_DB);
            ds.setPassword(URL_DB);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private Connection conectar() {
        return ds.getConnection();
    }

    public List<Marca> consultarMarca() {
        List<Marca> listaMarca = new ArrayList<>();
        try (
            Connection con = conectar();
            PreparedStatement ps = con.prepareStatement("SELECT NOME, ID FROM MARCA");
            ResultSet rs = ps.executeQuery()
        ) {
            while (rs.next()) {
                Marca marca = new Marca();
                marca.setNome(rs.getString("NOME"));
                marca.setMarcaID(rs.getInt("ID"));
                listaMarca.add(marca);
            }
        } catch (SQLException ex) {
            System.out.println("Erro: " + ex.getMessage());
            // ATENÇÃO: Comer exceções só dando um System.out.println nelas é uma má prática de programação!
        }
        return listaMarca;
    }

    public List<Carro> consultarModelos(Marca marcaSelecionada) {
        if (marcaSelecionada == null) throw new IllegalArgumentException("Nenhuma marca foi selecionada.");
        List<Carro> listaModelo = new ArrayList<>();
        try (
            Connection con = conectar();
            PreparedStatement ps = con.prepareStatement("SELECT C.CARROS_ID, C.CARROS_MODELO, M.NOME FROM CARROS C, MARCA M WHERE M.ID = C.CARROS_ID AND M.ID = ? ")
        ) {
            ps.setInt(1, marcaSelecionada.getMarcaID());
            try (ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                Carro carro = new Carro();
                carro.setId(rs.getInt("CARROS_ID"));
                carro.setModelo(rs.getString("CARROS_MODELO"));
                listaModelo.add(carro);
            }
        } catch (SQLException ex) {
            System.out.println("Erro: " + ex.getMessage());
            // ATENÇÃO: Comer exceções só dando um System.out.println nelas é uma má prática de programação!
        }
        return listaModelo;
    }
}

Keep the following in mind:

  • Do not repeat or copy and paste codes. Have in each method, repeated, the URL, the user, the password, the OracleDataSource , the Connection , etc. not a good thing. One of the ideas for which functions, procedures, and methods have been created is so that repeating things like these need only be coded once.

  • Use try-with-resources - it was created so that the logic of creating objects that need to be closed is not that difficult to code. And by the way, your logic to close the connections, statements , etc. was wrong, because if an exception occurs (ex: NullPointerException ), they remain open.

  • In your code there was this:

    carro.setId(++idCarro);
    

    Guess what would happen if you deleted a car from the database? He'd mess up the IDs! The solution to this is simply to get the database ID instead of counting the lines and assuming that this will match the expected IDs.

  • You were working with a variable ps and another stmt . You just need one.

  • In your original code, if you call the carrosDAO.consultarModelos(marcaSelecionada) method when marcaSelecionada is null , within DAO ps.setInt(1, marcaSelecionada.getMarcaID()); will give you a NullPointerException . I traded this for a friendlier exception. If this happens, you can be sure that the problem will not be in CarrosDAO , but in the managed bean .

I could not see something wrong with your XHTML, but you may have something there that you did not notice. I do not know if this will solve your problem, but at least it will make it easier and simpler.

    
10.01.2017 / 18:33