Nullpointexception in the register method

Asked

Viewed 77 times

1

Does anyone know how to solve this nullPointExcetion? In the second way I am using two combobox

Follows the class Clientedao

package DAO;

import Beans.ClienteBeans;
import Utilitarios.Conexao;
import Utilitarios.VerificacadoresEConrretores;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class ClienteDAO {

    public ClienteDAO() {

    }  

    public void cadastrarCliente(ClienteBeans cliente){
        try { 
            String SQLInsertion = "insert into cliente(cli_nome,cli_rua,cli_bairro,cli_telefone,cli_datacad)"
                + "values(?,?,?,?,?)";

            PreparedStatement stm = Conexao.getConnetion().prepareStatement(SQLInsertion);
            stm.setString(1, cliente.getNome()); 
            stm.setString(2, cliente.getRua());  
            stm.setString(3, cliente.getBairro()); 
            stm.setString(4, cliente.getTelefone()); 
            stm.setString(5, VerificacadoresEConrretores.converteparaSQL(cliente.getDataCad())); 
            stm.execute();  

            Conexao.getConnetion().commit();
            JOptionPane.showMessageDialog(null, "cadastrado com sucesso!","cadastro efetivado",1,new ImageIcon("Imagens/sucess.png"));

        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
        }
    }  
    // este metodo indica qual é o número do codigo do proximo cliente  que ser cadastrado
    public String proximoCliente(){
        try { 
            String SQLSelection = "select * from Cliente order by cli_cod desc limit 1;";
            PreparedStatement stm = Conexao.getConnetion().prepareCall(SQLSelection);
            ResultSet rs = stm.executeQuery();
            if(rs.next()){// se existe cliente cadastrado retorna o codigo do proximo cliente
                return (Integer.parseInt(rs.getString("cli_cod")) + 1 ) + "";// o + "" transforma os valores em String
            }
            else{// se nao existe ninguem cadastrado no sistema ele será o cliente de codigo 1 
                String SQLResetIncrement = "alter table cliente auto_increment = 1;";
                PreparedStatement stmIncrement = Conexao.getConnetion().prepareStatement(SQLResetIncrement);
                stmIncrement.execute();
                Conexao.getConnetion().commit();
                return "1";
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
            return "0";
        } 
    } 
    public void procurarCliente (String pesquisa, DefaultTableModel modelo){

    }
} 

Follows the class Functiodao

package DAO;

import Beans.FuncionarioBeans;
import Utilitarios.Conexao;
import Utilitarios.VerificacadoresEConrretores;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; 

public class FuncionarioDAO {

    public FuncionarioDAO() {

    }

    public void cadastrarFuncionario(FuncionarioBeans funcionario){

        try {
            String SQLInsertion = "insertion into funcionario (func_nome , func_cargo , func_permissao , func_datacad)"
                + "values(?,?,?,?)"; 

            PreparedStatement stm = Conexao.getConnetion().prepareStatement(SQLInsertion);
            stm.setString(1, funcionario.getNome());
            stm.setString(2, funcionario.getCargo());
            stm.setString(3, funcionario.getPermissao());
            stm.setString(5, VerificacadoresEConrretores.converteparaSQL(funcionario.getDataCad())); 

            stm.execute();   
            Conexao.getConnetion().commit();
            JOptionPane.showMessageDialog(null, "cadastrado com sucesso!","cadastro efetivado",1,new ImageIcon("Imagens/sucess.png"));

        }
        catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
        }
    }

    public String proximoFuncionario(){
        try { 
            String SQLSelection = "select * from funcionario order by func_cod desc limit 1;";
            PreparedStatement stm = Conexao.getConnetion().prepareCall(SQLSelection);
            ResultSet rs = stm.executeQuery();
            if(rs.next()){// se existe funcionario cadastrado retorna o codigo do proximo funcionario
                return (Integer.parseInt(rs.getString("func_cod")) + 1 ) + "";// o + "" transforma os valores em String
            }
            else{// se nao existe ninguem cadastrado no sistema ele será o cliente de codigo 1 
                String SQLResetIncrement = "alter table funcionario auto_increment = 1;";
                PreparedStatement stmIncrement = Conexao.getConnetion().prepareStatement(SQLResetIncrement);
                stmIncrement.execute();
                Conexao.getConnetion().commit(); 
                return "1";
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Impossivel cadastrar","Erro de SQL", 0, new ImageIcon("Imagens/cancelar.png"));
            return "0";
        }          
    }
}

Follows the Clientebeans class

package Beans;


public class ClienteBeans {

    private int codigo;  
    private String nome;
    private String rua;
    private String bairro;
    private String telefone; 
    private String dataCad;

    public ClienteBeans() {

    }

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public void setRua(String rua) {
        this.rua = rua;
    }

    public void setBairro(String bairro) {
        this.bairro = bairro;
    }

    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }

    public void setDataCad(String dataCad) {
        this.dataCad = dataCad;
    }

    public String getNome() {
        return nome;
    }

    public String getRua() {
        return rua;
    }

    public String getBairro() {
        return bairro;
    }

    public String getTelefone() {
        return telefone;
    }

    public String getDataCad() {
        return dataCad;
    } 
}

Follows the class Functiobeans

package Beans;

public class FuncionarioBeans {

    private int codigo; 
    private String nome;
    private String cargo;
    private String permissao;
    private String dataCad ;

    public FuncionarioBeans(){

    }

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCargo() {
        return cargo;
    }

    public void setCargo(String cargo) {
        this.cargo = cargo;
    }

    public String getPermissao() {
        return permissao;
    }

    public void setPermissao(String permissao) {
        this.permissao = permissao;
    }

    public String getDataCad() {
        return dataCad;
    }

    public void setDataCad(String dataCad){
        this.dataCad = dataCad;
    }
}

Follows the Clientecontroller class

package Controller;

import Beans.ClienteBeans;
import DAO.ClienteDAO;
import GUI.ClienteGUI;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class ClienteController {

    ClienteDAO clienteDao; 
    ClienteGUI clienteG;  

    public ClienteController() {
        clienteDao = new ClienteDAO();   
    }

    public boolean verificarDados(ClienteBeans cliente){ 
        if(cliente.getNome().equals("")){
            JOptionPane.showMessageDialog(null, "Campo Nome nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false;  
        }    

        if(cliente.getRua().equals("")){
            JOptionPane.showMessageDialog(null, "Campo Rua nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false;  
        }

        if(cliente.getBairro().equals("")){
            JOptionPane.showMessageDialog(null, "Campo Bairro nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false; 
        }
        if(cliente.getTelefone().equals("(  )     -     ")){
            JOptionPane.showMessageDialog(null, "Campo Telefone nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false; 
        }

        clienteDao.cadastrarCliente(cliente);     
        return true;
    } 
    public String controllerDeCodigo(){
        return clienteDao.proximoCliente();  
    }
    public void controlePesquisa(String pesquisa, DefaultTableModel modelo){
        //clienteDao.procurarCliente(pesquisa,modelo); 
    } 
    public ClienteBeans controlePreenchimento(int codigo){
        //return clienteDao.preencherCampos(codigo);
        return null;  // esta errado (foi apenas para nao motrar erro)
    }

    public void verificarDadosParaEditar(ClienteBeans cliente){
        //TODO
    }


}

Follows the Functioncontroller class

package Controller;

import Beans.FuncionarioBeans;
import DAO.FuncionarioDAO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class FuncionarioController {

    FuncionarioDAO funcionarioD; 

    public FuncionarioController() {
        funcionarioD =  new FuncionarioDAO();
    }   
    public String controllerDeCodigo(){
        return funcionarioD.proximoFuncionario();  
    }

    public boolean verificaDados(FuncionarioBeans funcionario, int cargo, int permissao ){
        if(funcionario.getNome().equals("")){
            JOptionPane.showMessageDialog(null, "Campo Nome nao pode ser vazio","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false;  
        }
        if(cargo == 0){
            JOptionPane.showMessageDialog(null, "Selecione um cargo","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false;
        } 
        if(permissao == 0){
            JOptionPane.showMessageDialog(null, "Selecione uma permissão!","Erro de preenchimento", 0, new ImageIcon("Imagens/cancelar.png"));
            return false;
        }

        funcionarioD.cadastrarFuncionario(funcionario);
        return true; 
    }
} 

Follows the class Verifiedbrokers

package Utilitarios;

import java.text.SimpleDateFormat;
import java.util.Date;

public class VerificacadoresEConrretores { 

    public static String converteparaSQL(String data){
        //dd/mm/aaaa // data no formato brasileiro
        //aaaa-mm-dd;  //         
        return data.substring(6,10)+ "-" +  data.substring(3,5)+ "-" + data.substring(0,2);
    }

    public static String converterParaJava(String data){
        return data.substring(8, 10) + "/" + data.substring(5, 7) + "/"+ data.substring(0, 4);
    } 

   public static String retornoDataAtual(){
       SimpleDateFormat formatoData = new SimpleDateFormat("dd/MM/yyyy");
       Date dataAtual = new Date();  
       return formatoData.format(dataAtual); 
   }
//    public static void main(String args[]){ 
//         System.out.println(VerificacadoresEConrretores.converterParaJava("2016/10/30"));
//    }
}

Follow the error

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Utilitarios.VerificacadoresEConrretores.converteparaSQL(VerificacadoresEConrretores.java:13)
    at DAO.FuncionarioDAO.cadastrarFuncionario(FuncionarioDAO.java:28)
    at Controller.FuncionarioController.verificaDados(FuncionarioController.java:33)
    at GUI.FuncionarioGUI.B_CadastrarActionPerformed(FuncionarioGUI.java:290)
    at GUI.FuncionarioGUI.access$600(FuncionarioGUI.java:8)
    at GUI.FuncionarioGUI$8.actionPerformed(FuncionarioGUI.java:141)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
CONSTRUÍDO COM SUCESSO (tempo total: 24 segundos)
  • I added friend,

  • Where is line 13 of the Verifier class?

  • This code here: Return data.substring(6,10)+ "-" + data.substring(3,5)+ "-" + data.substring(0,2);

  • Checked whether funcionario.getDataCad() is something really going on? By mistake, data is arriving null on this line 13.

  • getData() has no parameter. I think this nulpointexception must be caused because of the combobox of the registry methodFunctioning

  • The problem is that you are passing null to the method converteparaSQL, and seeing your code, null comes from funcionario.getDataCad() . However it does not have the origin of this function, so it is difficult to see where the error is. If possible, add a [mcve] code to be possible to test the problem.

  • Pretty, I’ll edit the question and add the rest of the code

  • The field dataCad of the Employee class is not being filled in, the code does not yet show when this class is filled in. Check that you are filling the object completely before submitting the Functionclass.

  • Thank you very much man, that was it. I was using Ctrl + C and Ctrl V in some codes I ended up forgetting to set ditches for the datacad. funcioB.setDataCad(Tf_data.gettext());

  • But I’m another problem, this caidno in Try cacht "Impossivel cadastra". I’ll see here

Show 5 more comments

2 answers

1


Look, in general exceptions of type nullPointExcetion arise when there is attempt to access there is an instance that null.

In your case, the indicated error starts at: 'CheckedutilitariansEConrretores.convertforSQL(Checked.java:13)', which is a method call that takes as a parameter the 'functio.getDataCad()'.

I recommend looking at whether there is an object being returned, by 'funcio.getDataCad()', or if it is null.

1

In class FuncionarioDAO, in the method cadastrarFuncionarios, has that line: stm.setString(5, VerificacadoresEConrretores.converteparaSQL(funcionario.getDataCad()));

In class FuncionarioController, in the validation method, you do not validate the attribute dataCad of FuncionarioBeans, therefore, if this attribute is null (which is probably what is happening), it goes unnoticed and only points out the exception when you use this attribute, which is in the method converteparaSQL, in class VerificacadoresEConrretores.

Implement a validation in your controller, make sure that this attribute is not null and the problem will no longer exist.

Browser other questions tagged

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