Exception in thread "AWT-Eventqueue-0" java.lang.Nullpointerexception to write to Mysql database

Asked

Viewed 445 times

0

Good evening, everyone!

I am having a problem recording the activity log of my system, the situation is the following the system is a multi user chat socket in my class that contains the graphical interface is the code that captures the access data.

Below is my Logmodel class

private int LOG_CODIGO;
private String LOG_USUARIO;
private String LOG_STATUS;
private String LOG_DATA;
private String LOG_HORA;
private String LOG_IPV4;
private String LOG_HOSTNAME;

public LogModel() {

}

public LogModel(int LOG_CODIGO, String LOG_USUARIO, String LOG_STATUS, String LOG_DATA, String LOG_HORA, String LOG_IPV4, String LOG_HOSTNAME) {
    this.LOG_CODIGO = LOG_CODIGO;
    this.LOG_USUARIO = LOG_USUARIO;
    this.LOG_STATUS = LOG_STATUS;
    this.LOG_DATA = LOG_DATA;
    this.LOG_HORA = LOG_HORA;
    this.LOG_IPV4 = LOG_IPV4;
    this.LOG_HOSTNAME = LOG_HOSTNAME;
}

public int getLOG_CODIGO() {
    return LOG_CODIGO;
}

public void setLOG_CODIGO(int LOG_CODIGO) {
    this.LOG_CODIGO = LOG_CODIGO;
}

public String getLOG_USUARIO() {
    return LOG_USUARIO;
}

public void setLOG_USUARIO(String LOG_USUARIO) {
    this.LOG_USUARIO = LOG_USUARIO;
}

public String getLOG_STATUS() {
    return LOG_STATUS;
}

public void setLOG_STATUS(String LOG_STATUS) {
    this.LOG_STATUS = LOG_STATUS;
}

public String getLOG_DATA() {
    return LOG_DATA;
}

public void setLOG_DATA(String LOG_DATA) {
    this.LOG_DATA = LOG_DATA;
}

public String getLOG_HORA() {
    return LOG_HORA;
}

public void setLOG_HORA(String LOG_HORA) {
    this.LOG_HORA = LOG_HORA;
}

public String getLOG_IPV4() {
    return LOG_IPV4;
}

public void setLOG_IPV4(String LOG_IPV4) {
    this.LOG_IPV4 = LOG_IPV4;
}

public String getLOG_HOSTNAME() {
    return LOG_HOSTNAME;
}

public void setLOG_HOSTNAME(String LOG_HOSTNAME) {
    this.LOG_HOSTNAME = LOG_HOSTNAME;
}

}

The class below is my class Logdao

public class Logdao {

private final Connection conexao;

public LogDao() {

    this.conexao = Conexao.getConexao();

}

public void adicionar(LogModel logmodel) throws SQLException {

    String SQL = "INSERT INTO LOG_ACESSO (LOG_USUARIO, LOG_STATUS, LOG_DATA, LOG_HORA, LOG_IPV4, LOG_HOSTNAME) VALUES (?,?,?,?,?,?)";

    PreparedStatement stmt = conexao.prepareStatement(SQL);
    stmt.setString(1, logmodel.getLOG_USUARIO());
    stmt.setString(2, logmodel.getLOG_STATUS());
    stmt.setString(3, logmodel.getLOG_DATA());
    stmt.setString(4, logmodel.getLOG_HORA());
    stmt.setString(5, logmodel.getLOG_IPV4());
    stmt.setString(6, logmodel.getLOG_HOSTNAME());

    stmt.executeUpdate();
    stmt.close();
}    

}

The lower class is my connection class

public class Connexion {

private final static String DRIVER = "com.mysql.jdbc.Driver";
private final static String BANCO = "jdbc:mysql://10.10.10.7/CHAT";
private final static String USUARIO = "carpezani";
private final static String SENHA = "1q2w3e4r5t";

private static Connection conexao;

public Conexao() {
    try {

        Class.forName(DRIVER);
        conexao = DriverManager.getConnection(BANCO, USUARIO, SENHA);

    } catch (ClassNotFoundException ex) {

        JOptionPane.showMessageDialog(null, "Erro na classe de conexão do banco. \n" + ex.getMessage());
        conexao = null;

    } catch (SQLException ex) {

        JOptionPane.showMessageDialog(null, "Erro ao conectar no banco.\n" + ex.getMessage());
        conexao = null;
    }
}

public static Connection getConexao() {

    return conexao;
}

public static void fecharConexao() {
    try {

        conexao.close();

    } catch (SQLException ex) {

        System.out.println("Falha ao fechar conexao.\n" + ex.getMessage());
    }
}

}

And the connect button event that captures the information and plays for the database.

private void btnCONECTARActionPerformed(java.awt.Event.Actionevent evt) {

    String nome = this.edtCONEXAO.getText(); // variavel recebendo infomação do usuario

    // validação de conexão
    if (nome.isEmpty()) {

        JOptionPane.showMessageDialog(this, "Por favor, informe o usuário!", "Mensagem",
                JOptionPane.WARNING_MESSAGE);

    } else {

        this.menssagem = new ChatMenssagem(); // inicilização do ChatMenssagem
        this.menssagem.setAction(Action.CONECTADO); // faz a requisição de conexão.
        this.menssagem.setNome(nome); // nome do usuario que foi digitado na interface

        this.service = new ChatService(); // inicializar a classe ChatService
        this.socket = this.service.conexao(); // retornando um socket

        new Thread(new ListenerSocket(this.socket)).start();  // objeto socket é passado para a Thread

        this.service.Send(menssagem); // retorno da mensagem
    }

    try {

        LogModel logmodel = new LogModel();

        logmodel.setLOG_CODIGO(Integer.parseInt(lblCODIGO.getText()));
        logmodel.setLOG_USUARIO(edtCONEXAO.getText());
        logmodel.setLOG_STATUS(edtCONEXAO.getText());
        logmodel.setLOG_DATA(lblDATA.getText());
        logmodel.setLOG_HORA(lblHORA.getText());
        logmodel.setLOG_IPV4(lblIPV4.getText());
        logmodel.setLOG_HOSTNAME(lblHOSTNAME.getText());

        LogDao dao = new LogDao();
        dao.adicionar(logmodel);

    } catch (SQLException erro) {

        JOptionPane.showMessageDialog(this, "Erro:" + erro.getMessage(), "Erro",
                JOptionPane.ERROR_MESSAGE);
    }

}

And finally the error that is appearing on the console.

Exception in thread "AWT-Eventqueue-0" java.lang.Nullpointerexception at com.aps.app.dao.Logdao.add(Logdao.java:23) at com.aps.app.frame.chatjanela.btnCONECTARActionPerformed(Chatjanela.java:430) at com.aps.app.frame.Chatjanela.access$500(Chatjanela.java:33) at com.aps.app.frame.Chatjanela$1.actionPerformed(Chatjanela.java:244) at javax.swing.Abstractbutton.fireActionPerformed(Abstractbutton.java:2022) at javax.swing.Abstractbutton$Handler.actionPerformed(Abstractbutton.java:2348) 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.Awteventmulticaster.mouseReleased(Awteventmulticaster.java:289) at java.awt.Component.processMouseEvent(Component.java:6539) at javax.swing.Jcomponent.processMouseEvent(Jcomponent.java:3324) at java.awt.Component.processEvent(Component.java:6304) at java.awt.Container.processEvent(Container.java:2239) at java.awt.Component.dispatchEventImpl(Component.java:4889) at java.awt.Container.dispatchEventImpl(Container.java:2297) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.Lightweightdispatcher.retargetMouseEvent(Container.java:4904) at java.awt.Lightweightdispatcher.processMouseEvent(Container.java:4535) at java.awt.Lightweightdispatcher.dispatchEvent(Container.java:4476) at java.awt.Container.dispatchEventImpl(Container.java:2283) at java.awt.Window.dispatchEventImpl(Window.java:2746) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.Eventqueue.dispatchEventImpl(Eventqueue.java:760) 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$Javasecurityaccessimpl.doIntersectionPrivilege(Protectiondomain.java:74) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Protectiondomain.java:84) at java.awt.Eventqueue$4.run(Eventqueue.java:733) at java.awt.Eventqueue$4.run(Eventqueue.java:731) at java.security.Accesscontroller.doPrivileged(Native Method) at java.security.Protectiondomain$Javasecurityaccessimpl.doIntersectionPrivilege(Protectiondomain.java:74) at java.awt.Eventqueue.dispatchEvent(Eventqueue.java:730) at java.awt.Eventdispatchthread.pumpOneEventForFilters(Eventdispatchthread.java:205) 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)

Guys if anyone can help me I appreciate from now on.

1 answer

1

Apparently your connection is null when you call through Connexion.getConexao(), as it is a static method it does not pass by the constructor which is where you create the connection, I suggest a look at the Singleton Pattern for what you are trying to do

  • I ended up debugging and ended up visualizing that the connection was null even, will be that if I take Static of the method would solve?

  • yes, in that case yes

  • I withdrew, but he complained in the Logdao class in that stretch

  • public Logdao() { this.connection = Connection.getConnected(); }

  • in this case is that since it ceased to be Static you have to instantiate the connected class

  • Beauty I’ll try here

  • Old worked out, thank you very seriously!

  • Basically you are a java kkkk god worth brother.

  • Opa que isso man sou mero aprendiz ainda, tentada da um olhar no Pattern Singleton para usar na sua classe conexão

Show 4 more comments

Browser other questions tagged

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