Nullpointerexception Selectonemenu [JSF + PRIMEFACES]

Asked

Viewed 470 times

0

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

UPDATED ( JA NO BEAN MANEGED COMING NULL). After I get out of the way Query() of the DAO the Selected tag is null when I selected the other menu to get the value related to the first menu "markerSelected" (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 the 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 you are 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)
  • Related, I recommend reading to simplify your DAO: http://answall.com/a/172910/132

  • Put a breakpoint in the method of loading the templates and see if it is triggered when selecting the brand.

  • Which line launches the Exception? You have debugged to see if the parameter marcaSelecionada comes filled correctly? It is not null?

  • @Douglas is triggered yes, and comes from Nell Pointer in the Dão method for fetching modekos brandSelected.getName on this line to be exact.

  • @igorventurelli already debugged tagSelected comes null in MB and In DAO also when I call dialSelected.getName in model query

  • Post the complete Managedbean code, please.

  • @igorventurelli Igor for this select one menu only uses these two methods so do not put all.

  • Post the get&set of attributes that have relation then, please.

  • @igorventurelli ta there would be only those involved

  • Thanks! Try to take the event="change" from the ajax, please.

  • @igorventurelli had already done this, tried again and nothing.

  • In the Bean, in the variable declaration, incise it with a new instance. Please. private Marca marcaSelecionada = new Marca(); and in the method carregarModelos() make a System.out.println(marcaSelecionada); before consulting the bank.

  • When initializing with a new instance it gives the error Jan 11, 2017 10:20:37 AM with.sun.faces.application.view.Faceletviewhandlingstrategy handleRenderException Grave: Error Rendering View[/telaDeVendas.xhtml] java.lang.Classcastexception: Entity.Brand cannot be cast to Entity.Car

  • https://github.com/rodrigoscsx/LojaDeCarros The project here is with source and html

Show 9 more comments

1 answer

1

Dude, I redid your whole 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 in mind the following:

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

  • Use the Try-with-Resources - it was created so that the logic of creating objects that need to be closed is not so difficult to encode. And by the way, your logic for closing connections, statements, etc was wrong, because if an exception occurs (ex: NullPointerException), they remained open.

  • In your code there was this:

    carro.setId(++idCarro);
    

    Guess what would happen if you deleted a car from the database? It would mess up the Ids! The solution to this is to simply take the database ID instead of counting the lines and assume it will match the expected Ids.

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

  • In its original code, if you call the method carrosDAO.consultarModelos(marcaSelecionada) when marcaSelecionada for null, within the DAO o o ps.setInt(1, marcaSelecionada.getMarcaID()); will give you a NullPointerException. I traded this for a more friendly exception. If this happens, you can be sure that the problem will not be in the CarrosDAO, and yes in the Managed bean.

I couldn’t see anything wrong with your XHTML, but there might be something there that you missed. I don’t know if this will solve your problem, but at least it will make things easier and simpler.

  • Good evening Thank you for the guidelines I will change that there , and I tell you . for what I saw makes perfect sense. The car.setId(++idCarro); was a friend who put convert nut

  • Good morning I wanted to thank the tips finishing this project I will save on the lines and let the program more elegant with that there. I saw here that The problem should be in the view because in the bean Managed it is already null when giving a getMarcaSelected();

  • github.com/rodrigoscsx/Lojadecarros Projeto

Browser other questions tagged

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