Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

4 respostas
S

Bom dia, por favor me ajudem, sou novo em java e Estou criando um sistema bem simples de cadastro de usuário que irá armazenas as informações no SQL sever, só que está dando o seguinte erro:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at dao.UsuarioDAO.adiciona(UsuarioDAO.java:23)
	at gui.UsuarioGUI.btnCadastrarActionPerformed(UsuarioGUI.java:212)
	at gui.UsuarioGUI.access$000(UsuarioGUI.java:16)
	at gui.UsuarioGUI$1.actionPerformed(UsuarioGUI.java:73)
	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.Component.processMouseEvent(Component.java:6535)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
	at java.awt.Component.processEvent(Component.java:6300)
	at java.awt.Container.processEvent(Container.java:2236)
	at java.awt.Component.dispatchEventImpl(Component.java:4891)
	at java.awt.Container.dispatchEventImpl(Container.java:2294)
	at java.awt.Component.dispatchEvent(Component.java:4713)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
	at java.awt.Container.dispatchEventImpl(Container.java:2280)
	at java.awt.Window.dispatchEventImpl(Window.java:2750)
	at java.awt.Component.dispatchEvent(Component.java:4713)
	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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
	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)

Segue o código da linha 23 que está dando erro:

package dao; 

import factory.ConnectionFactory; 
import modelo.Usuario; 
import java.sql.*; 
import java.sql.PreparedStatement; 

public class UsuarioDAO {     
    private Connection connection;     
    Long id;     
    String nome;     
    String cpf;     
    String email;     
    String telefone;    
    
    public UsuarioDAO(){       
        this.connection = new ConnectionFactory().getConnection();     
    }     
    
    public void adiciona(Usuario usuario){      
        String sql = "INSERT INTO usuario(nome,cpf,email,telefone) VALUES(?,?,?,?)"; 
        try {            
           PreparedStatement stmt = connection.prepareStatement(sql); //Essa é a linha 23
            stmt.setString(1, usuario.getNome()); 
            stmt.setString(2, usuario.getCpf());           
            stmt.setString(3, usuario.getEmail());            
            stmt.setString(4, usuario.getTelefone());            
            stmt.execute();            
            stmt.close();
        } catch (SQLException u) { 
            throw new RuntimeException(u);         
        }     
    } 
}

Segue o código da linha 212 que está dando erro:

Usuario usuarios = new Usuario(); 
        usuarios.setNome(txtCampo1.getText()); 
        usuarios.setCpf(txtCampo2.getText()); 
        usuarios.setEmail(txtCampo3.getText()); 
        usuarios.setTelefone(txtCampo4.getText()); // fazendo a validação dos dados 
        
        if ((txtCampo1.getText().isEmpty()) || (txtCampo2.getText().isEmpty()) || (txtCampo3.getText().isEmpty()) || (txtCampo4.getText().isEmpty())) {    
            JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios");
        }  else { // instanciando a classe UsuarioDAO do pacote dao e criando seu objeto dao  
    
    UsuarioDAO dao = new UsuarioDAO();  
    dao.adiciona(usuarios);              //Essa é a linha 212
    JOptionPane.showMessageDialog(null, "Usuário "+txtCampo1.getText()+" inserido com sucesso! "); 
        } // apaga os dados preenchidos nos campos de texto 
        
       txtCampo1.setText("");
       txtCampo2.setText("");
       txtCampo3.setText("");
       txtCampo4.setText("");

        }

A linha 16 é o "public class UsuarioGUI extends javax.swing.JFrame { "

e a linha 73 é o

public void actionPerformed(java.awt.event.ActionEvent evt) {

btnCadastrarActionPerformed(evt);

}

Por favor, me ajudem.

4 Respostas

pmlm

A variavel connection está a null na hora da execução do SQL.

murilo_galvao

esse teu cara não ta instanciando connection da maneira correta, da uma verificada nele, pq do jeito q ele ta acontece oq o @pmlm comentou acima, a sua variável connection fica como null.

S

Mais como posso concertar isso?
Segue só minha conexão com o banco de dados da minha classe ConnectionFactory:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package factory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Silas
 */
public class ConnectionFactory {
    
    private Connection conexao;

      public static void main(String[] args) throws SQLException {
          
          
      String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
      "databaseName=SistemaCadastro";

    try {
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
      Connection conn = DriverManager.getConnection(connectionUrl, "sa", "303040");
      System.out.println("Conexão obtida com sucesso.");
    }
    catch (SQLException ex) {
      System.out.println("SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
      
    }
    catch (Exception e) {
      System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
    }
      }

    public Connection getConnection() {
       return conexao;
    }
    

  

   
}

Segue abaixo o script da minha classe UsuarioDAO:

package dao; 

import factory.ConnectionFactory; 
import modelo.Usuario; 
import java.sql.*; 
import java.sql.PreparedStatement; 

public class UsuarioDAO {     
    private Connection connection;     
    Long id;     
    String nome;     
    String cpf;     
    String email;     
    String telefone;    
    
    public UsuarioDAO() throws ClassNotFoundException, SQLException{       
        this.connection = new ConnectionFactory().getConnection();     
    }     
    
    public void adiciona(Usuario usuario){      
        String sql = "INSERT INTO usuario(nome,cpf,email,telefone) VALUES(?,?,?,?)"; 
        try {            
            PreparedStatement stmt = connection.prepareStatement(sql); 
            stmt.setString(1, usuario.getNome()); 
            stmt.setString(2, usuario.getCpf());           
            stmt.setString(3, usuario.getEmail());            
            stmt.setString(4, usuario.getTelefone());            
            stmt.execute();            
            stmt.close();
        } catch (SQLException u) { 
            throw new RuntimeException(u);         
        }     
    } 
}
S

O tópico pode ser fechado, eu agradeço muito pelas ajudas.
Caso alguém esteja com o mesmo problema, depois de tanto pesquisar(desde ontem a noite), eu consegui fazer da seguinte forma.

Na classe de conexão:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package factory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Silas
 */
public class ConnectionFactory {
    
    
    
     public Connection getConnection() {
        try {
            return DriverManager.getConnection(
         "jdbc:sqlserver://localhost:1433;" +
      "databaseName=SistemaCadastro", "sa", "303040");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
   
}

Na classe de UsuarioDAO:

package dao; 

import factory.ConnectionFactory; 
import modelo.Usuario; 
import java.sql.*; 
import java.sql.PreparedStatement; 

public class UsuarioDAO {     
    private Connection connection;     
    Long id;     
    String nome;     
    String cpf;     
    String email;     
    String telefone;    
    
    public UsuarioDAO() {       
        this.connection = new ConnectionFactory().getConnection();     
    }     
    
    public void adiciona(Usuario usuario){      
        String sql = "INSERT INTO usuario(nome,cpf,email,telefone) VALUES(?,?,?,?)"; 
        try {            
            PreparedStatement stmt = connection.prepareStatement(sql); 
            stmt.setString(1, usuario.getNome()); 
            stmt.setString(2, usuario.getCpf());           
            stmt.setString(3, usuario.getEmail());            
            stmt.setString(4, usuario.getTelefone());            
            stmt.execute();            
            stmt.close();
        } catch (SQLException u) { 
            throw new RuntimeException(u);         
        }     
    } 
}

E para funcionar você tem que ter o sqljdbc4 como sua biblioteca no netbeans.

Criado 22 de abril de 2016
Ultima resposta 22 de abr. de 2016
Respostas 4
Participantes 3