[Resolvido]Java null exception point

12 respostas
A

Boa noite, gostaria que alguém me ajudasse com um erro que estou tendo na programação java.

//
/*

  • 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 br.com.mrecearia.telas;
import br.com.mrecearia.dal.ConexaoBanco;

import java.awt.Color;

import java.sql.*;

import javax.swing.JOptionPane;

/**

*
  • @author Alvaro Silva
    */
    public class TelaLogin extends javax.swing.JFrame {

    Connection conexao = null;
    
    PreparedStatement pst = null;
    
    ResultSet rs = null;
    

    public void logar() {
    String sql = “select * from usuario where usuario=? and senha = ?”;

    try {
         pst = conexao.prepareStatement(sql);// o debug indicou o erro aqui, indicou nulo
         pst.setString(1, txtUsuario.getText());
         pst.setString(2, txtSenha.getText());
         rs = pst.executeQuery();
         
         if (rs.next()) { 
             TelaPrincipal principal = new TelaPrincipal();
             principal.setVisible(true);
             
             } else {
                 JOptionPane.showMessageDialog(null, "Usuario ou senha incorretos!");
             }
                     
     } catch (Exception e) {
         JOptionPane.showMessageDialog(null, e);
     }
    

    }
    /**

    • Creates new form TelaLogin
      */
      public TelaLogin() {
      initComponents();
      conexao = ConexaoBanco.conector();

    }

    /**

    • This method is called from within the constructor to initialize the form.

    • WARNING: Do NOT modify this code. The content of this method is always

    • regenerated by the Form Editor.
      
      */
      
      @SuppressWarnings(unchecked)
      
      // 
      
      private void initComponents() {
      
      jPanel1 = new javax.swing.JPanel();
      
      lblUsuario = new javax.swing.JLabel();
      
      lblSenha = new javax.swing.JLabel();
      
      txtUsuario = new javax.swing.JTextField();
      
      txtSenha = new javax.swing.JPasswordField();
      
      btnEntrar = new javax.swing.JToggleButton();
      

      setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
      setResizable(false);

      lblUsuario.setFont(new java.awt.Font(“Verdana”, 1, 14)); // NOI18N
      lblUsuario.setText(“Usuario”);

      lblSenha.setFont(new java.awt.Font(“Verdana”, 1, 14)); // NOI18N
      lblSenha.setText(“Senha”);

      txtUsuario.setFont(new java.awt.Font(Verdana, 0, 14)); // NOI18N
      
      txtUsuario.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      txtUsuarioActionPerformed(evt);
      
      }
      
      });
      

      txtSenha.setFont(new java.awt.Font(“Verdana”, 0, 14)); // NOI18N

      btnEntrar.setFont(new java.awt.Font(Tahoma, 1, 14)); // NOI18N
      
      btnEntrar.setText(Entrar);
      
      btnEntrar.addActionListener(new java.awt.event.ActionListener() {
      
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      
      btnEntrarActionPerformed(evt);
      
      }
      
      });
      
      javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
      
      jPanel1.setLayout(jPanel1Layout);
      
      jPanel1Layout.setHorizontalGroup(
      
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addGroup(jPanel1Layout.createSequentialGroup()
      
      .addGap(102, 102, 102)
      
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
      
      .addComponent(btnEntrar)
      
      .addGroup(jPanel1Layout.createSequentialGroup()
      
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
      
      .addComponent(lblUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      
      .addComponent(lblSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
      
      .addGap(45, 45, 45)
      
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
      
      .addComponent(txtUsuario)
      
      .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE))))
      
      .addContainerGap(104, Short.MAX_VALUE))
      
      );
      
      jPanel1Layout.setVerticalGroup(
      
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
      
      .addContainerGap(80, Short.MAX_VALUE)
      
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addComponent(lblUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      
      .addGap(36, 36, 36)
      
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      
      .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
      
      .addComponent(lblSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
      
      .addGap(38, 38, 38)
      
      .addComponent(btnEntrar)
      
      .addGap(73, 73, 73))
      
      );
      
      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      
      getContentPane().setLayout(layout);
      
      layout.setHorizontalGroup(
      
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      
      );
      
      layout.setVerticalGroup(
      
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      
      .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      
      );
      
      pack();
      
      setLocationRelativeTo(null);
      
      }//
      
    private void txtUsuarioActionPerformed(java.awt.event.ActionEvent evt) {
    
    // TODO add your handling code here:
    
    }
    
    private void btnEntrarActionPerformed(java.awt.event.ActionEvent evt) {
    
    logar();
    
    }
    

    /**

    • @param args the command line arguments
      /
      public static void main(String args[]) {
      /
      Set the Nimbus look and feel /
      //
      /
      If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

      • For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
        */
        try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if (“Nimbus”.equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
        }
        }
        } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(TelaLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //
      /* Create and display the form */
      
      java.awt.EventQueue.invokeLater(new Runnable() {
      
      public void run() {
      
      new TelaLogin().setVisible(true);
      
      }
      
      });
      
      }
      
    // Variables declaration - do not modify
    
    private javax.swing.JToggleButton btnEntrar;
    
    private javax.swing.JPanel jPanel1;
    
    private javax.swing.JLabel lblSenha;
    
    private javax.swing.JLabel lblUsuario;
    
    private javax.swing.JPasswordField txtSenha;
    
    private javax.swing.JTextField txtUsuario;
    
    // End of variables declaration
    
    }
    

12 Respostas

rodriguesabner

E aí Alvaro, boa noite.

Cara, postar o código assim e pedir ajuda fica meio tenso. Posta o erro aqui também.

Jederson_Andre

Eu costumo faver a sql, indicando o nome da base e tabela, assim:

select nome, nickaname, pass from nomeDaBase.nomeDaTabela where nickname =? AND pass=?;

Outra coisa… antes de entrar no IF, faz a impressão da sql, pra ver se ela está correta.

System.out.println(sql);
A

Então Abner só aparece esse erro.

java.lang.NullPointerException

pois o problema não está no código e sim na conexão com o banco de dados.

T

Olá

Qual a versão e o banco de dados utilizado?

Posta o código de conexão com o BD e o erro completo apresentado após a execução da aplicação para que seja possível verificar a exceção.

A

versão do banco: mysql workbench 8.0.
código da conexão:

public static Connection conector(){
java.sql.Connection conexao = null;

String driver = "com.mysql.jdbc.Driver";

        String  url = "jdbc:mysql://localhost:3306/funcionario?useTimezone=true&serverTimezone=UTC";
        String  user = "root";
        String senha = "";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conexao= DriverManager.getConnection(url, user,senha);
            return conexao;
        } catch (ClassNotFoundException | SQLException e) {

            return null;
        }
        
    }

 }

Quando testo ele, eu coloco o usuario e a senha ai ele aparece somente essa mensagem abaixo:

java.lang.NullPointerException

T

No seu try … catch do método de conexão com o BD:

Tente fazer o seguinte:

try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conexao= DriverManager.getConnection(url, user,senha);
    } catch (ClassNotFoundException | SQLException e) {
        System.out.print("Erro Driver: " + e);
    }
   return conexao;

Se gerar erro, posta para que possa verificar.

A

Agora apareceu esse erro

Erro Conexão: java.lang.ClassNotFoundException: DRIVER

Jederson_Andre

Qual a versão do JConector??

A

versão 8.0.12

A

Gente consegui resolver, mais ou menos, eu esqueci de adicionar a buid path do conector, mas agora o eclipse está reclamando disso:

Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

Agora está funcionando, mas isso que está acima é ruin?

T

Boa noite
Corrige o Class.forName conforme lhe expliquei no post anterior.

A nova versão do MySQL mudou o caminho de acesso ao DRIVER.

A

Obrigado

Criado 18 de novembro de 2018
Ultima resposta 21 de nov. de 2018
Respostas 12
Participantes 4