Não, pois o NullPointerException é disparado sempre que tentamos utilizar um objeto nulo, no seu caso acredito que seja o resultset.
Mas para desencargo de consciência, faz debug da sua aplicação e acompanha passo a passo que você vai conseguir visualizar pontos que estão errados de maneira bem fácil.
Usuario Usuario = new Usuario();
Usuario.setNome(camponome.getText());
Usuario.setCpf(campocpf.getText());
Usuario.setEndereco(campoend.getText());
Usuario.setTel1(campotel1.getText());
Usuario.setTel2(campotel2.getText());
Usuario.setEmail(campoemail.getText());
Usuario.setPerfil((String) campoperf.getSelectedItem());
Usuario.setUsuario(campousu.getText());
Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
} else {
String sql = "Select * FROM usuarios where cpf like "+campocpf.getText();
try {
pst=conexao.prepareStatement(sql);
pst.setString(2,campocpf.getText());
rs=pst.executeQuery();
if (rs.first()) {
if (rs.equals(sql)) {
JOptionPane.showMessageDialog(null, “CPF já está cadastrado.”);
} else {
if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
UsuarioDAO DAO = new UsuarioDAO();
DAO.cadastrarusuario(Usuario);
JOptionPane.showMessageDialog(null, “Usuário " + camponome.getText() + " cadastrado com sucesso!”);
camponome.setText(null);
campocpf.setText(null);
campoend.setText(null);
campotel1.setText(null);
campotel2.setText(null);
campoemail.setText(null);
campousu.setText(null);
camposenha.setText(null);
campoconfsenha.setText(null);
} else {
JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Outra tentativa, permanece o java.lang…
Você não está fazendo nada com a vaiável sql
.
Onde e como você inicializou a variável rs
?
Em princípio é a implementação do método cadastrarusuario
que deveria verificar se já existe aquele usuário na base de dados.
Boa noite, Luiz Henrique
Conseguiu resolver mano? Caso não, me avisa que te ajudo com mais calma.
Vlw!
nada foi resolvido
Consegui não mano, o novo código ficou assim:
Usuario Usuario = new Usuario();
Usuario.setNome(camponome.getText());
Usuario.setCpf(campocpf.getText());
Usuario.setEndereco(campoend.getText());
Usuario.setTel1(campotel1.getText());
Usuario.setTel2(campotel2.getText());
Usuario.setEmail(campoemail.getText());
Usuario.setPerfil((String) campoperf.getSelectedItem());
Usuario.setUsuario(campousu.getText());
Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
} else {
String sql = "SELECT * FROM USUARIOS WHERE CPF LIKE '" + campocpf.getText().trim() + "' ";
try {
pst=conexao.prepareStatement(sql);
rs=pst.executeQuery();
if (rs.first()) {
JOptionPane.showMessageDialog(null, "CPF já está cadastrado.");
} else {
if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
UsuarioDAO DAO = new UsuarioDAO();
DAO.cadastrarusuario(Usuario);
JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
camponome.setText(null);
campocpf.setText(null);
campoend.setText(null);
campotel1.setText(null);
campotel2.setText(null);
campoemail.setText(null);
campousu.setText(null);
camposenha.setText(null);
campoconfsenha.setText(null);
} else {
JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Bom dai Luiz, faz o seguinte:
coloca todo o metodo no post pq não da para identificar neste trecho de cod onde vc cria o ResultSet e a Conexao
descreve o erro que vc esta tomando coloca o log do erro ou a mensagem que vc tah tomando no seu editor de cod
tendo isso consigo te ajudar
// TENTA USAR ESSE CÓDIGO... JÁ VAI TE DÁ UMA IDEIA.
Usuario usuario = new Usuario();
usuario.setNome(camponome.getText());
usuario.setCpf(campocpf.getText());
usuario.setEndereco(campoend.getText());
usuario.setTel1(campotel1.getText());
usuario.setTel2(campotel2.getText());
usuario.setEmail(campoemail.getText());
usuario.setPerfil((String) campoperf.getSelectedItem());
usuario.setUsuario(campousu.getText());
usuario.setSenha(camposenha.getText());
if (usuario.getNome().getText().equals(" ") || usuario.getCpf().getText().equals(" ") || usuario.getEndereco().getText().equals(" ") || usuario.getTel1().getText().equals(" ") || usuario.getEmail().getText().equals(" ") || usuario.getUsuario().getText().equals(" ") || usuario.getSenha().getText().equals(" ")) {
JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
} else {
try {
pst = conexao.prepareStatement("select cpf from usuarios where cpf = ?;");
pst.setString(usuario.getCpf().getText());
rs = pst.executeQuery();
if (rs.next()) {
String cpf = rs.getString(1); // AQUI VOCÊ COLOCA O NUMERO DA COLUNA CPF NA SUA TABELA.
if (cpf.equals(usuario.getCpf().getText())) {
JOptionPane.showMessageDialog(null, "O CPF JÁ ESTÁ CADASTRADO!");
} else {
if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
UsuarioDAO DAO = new UsuarioDAO();
DAO.cadastrarusuario(Usuario);
JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
camponome.setText(null);
campocpf.setText(null);
campoend.setText(null);
campotel1.setText(null);
campotel2.setText(null);
campoemail.setText(null);
campousu.setText(null);
camposenha.setText(null);
campoconfsenha.setText(null);
} else {
JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Dá pra melhorar esse código.
Faz essa consulta se o CPF já esta cadastrado tudo dentro do seu método DAO.cadastrarusuario(usuario).
Depois que você verifica se os campos estão preenchidos ou não, chama só o método.
A parte de conexão tenta deixar tudo dentro da sua classe DAO.
Vlw!
package GUI;
import java.sql.Connection;
import ping.Usuario;
import DAO.UsuarioDAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class CadastroUsuarios extends javax.swing.JFrame {
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
public CadastroUsuarios() {
initComponents();
}
/**
* 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")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
camponome = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
campocpf = new javax.swing.JFormattedTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
campoemail = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
campotel2 = new javax.swing.JFormattedTextField();
campotel1 = new javax.swing.JFormattedTextField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
campoperf = new javax.swing.JComboBox<>();
BtnCad = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
campousu = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
camposenha = new javax.swing.JPasswordField();
campoconfsenha = new javax.swing.JPasswordField();
campoend = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel1.setText("Nome:");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 50, -1, -1));
getContentPane().add(camponome, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 45, 635, -1));
jLabel2.setText("CPF:");
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, -1, -1));
try {
campocpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
getContentPane().add(campocpf, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 95, 130, -1));
jLabel3.setText("Endereço:");
getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, -1, -1));
jLabel4.setText("Email:");
getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 200, -1, -1));
getContentPane().add(campoemail, new org.netbeans.lib.awtextra.AbsoluteConstraints(68, 195, 470, -1));
jLabel5.setText("Telefone 1:");
getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 100, -1, -1));
campotel2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));
campotel2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
campotel2MouseClicked(evt);
}
});
campotel2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
campotel2ActionPerformed(evt);
}
});
campotel2.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
campotel2KeyPressed(evt);
}
});
getContentPane().add(campotel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(505, 95, 130, -1));
try {
campotel1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#####-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
getContentPane().add(campotel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(285, 95, 130, -1));
jLabel6.setText("Telefone 2:*");
getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 100, -1, -1));
jLabel7.setText("Perfil:");
getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 200, -1, -1));
campoperf.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Administrador", "Ajudante" }));
getContentPane().add(campoperf, new org.netbeans.lib.awtextra.AbsoluteConstraints(595, 195, 110, -1));
BtnCad.setText("Cadastrar");
BtnCad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnCadActionPerformed(evt);
}
});
getContentPane().add(BtnCad, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 420, 120, 60));
jLabel8.setText("Usuário:");
getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 250, -1, -1));
getContentPane().add(campousu, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 245, 150, -1));
jLabel9.setText("Senha:");
getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 300, -1, -1));
jLabel10.setText("Confirme sua senha:");
getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 350, -1, -1));
getContentPane().add(camposenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(73, 295, 120, -1));
getContentPane().add(campoconfsenha, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 345, 120, -1));
getContentPane().add(campoend, new org.netbeans.lib.awtextra.AbsoluteConstraints(85, 145, 610, -1));
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void BtnCadActionPerformed(java.awt.event.ActionEvent evt) {
Usuario Usuario = new Usuario();
Usuario.setNome(camponome.getText());
Usuario.setCpf(campocpf.getText());
Usuario.setEndereco(campoend.getText());
Usuario.setTel1(campotel1.getText());
Usuario.setTel2(campotel2.getText());
Usuario.setEmail(campoemail.getText());
Usuario.setPerfil((String) campoperf.getSelectedItem());
Usuario.setUsuario(campousu.getText());
Usuario.setSenha(camposenha.getText());
if ((camponome.getText().isEmpty()) || (campoend.getText().isEmpty()) || (campocpf.getText().isEmpty()) || (campotel1.getText().isEmpty()) || (campoemail.getText().isEmpty()) || (campousu.getText().isEmpty()) || (camposenha.getText().isEmpty()) || (campoconfsenha.getText().isEmpty())) {
JOptionPane.showMessageDialog(null, "Os campos não podem retornar vazios!", "Atenção", JOptionPane.WARNING_MESSAGE);
} else {
String sql = "SELECT * FROM USUARIOS WHERE CPF LIKE '" + campocpf.getText().trim() + "' ";
try {
pst=conexao.prepareStatement(sql);
pst.setString(1, campocpf.getText());
rs=pst.executeQuery();
if (rs.first()) {
JOptionPane.showMessageDialog(null, "CPF já está cadastrado.");
} else {
if (new String(camposenha.getPassword()).equals(new String(campoconfsenha.getPassword()))) {
UsuarioDAO DAO = new UsuarioDAO();
DAO.cadastrarusuario(Usuario);
JOptionPane.showMessageDialog(null, "Usuário " + camponome.getText() + " cadastrado com sucesso!");
camponome.setText(null);
campocpf.setText(null);
campoend.setText(null);
campotel1.setText(null);
campotel2.setText(null);
campoemail.setText(null);
campousu.setText(null);
camposenha.setText(null);
campoconfsenha.setText(null);
} else {
JOptionPane.showMessageDialog(null, "Senhas não conferem!", "Atenção", JOptionPane.WARNING_MESSAGE);
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
private void campotel2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void campotel2MouseClicked(java.awt.event.MouseEvent evt) {
try {
campotel2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)#####-####")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
}
private void campotel2KeyPressed(java.awt.event.KeyEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* 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(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CadastroUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CadastroUsuarios().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton BtnCad;
private javax.swing.JPasswordField campoconfsenha;
private javax.swing.JFormattedTextField campocpf;
private javax.swing.JTextField campoemail;
private javax.swing.JTextField campoend;
private javax.swing.JTextField camponome;
private javax.swing.JComboBox<String> campoperf;
private javax.swing.JPasswordField camposenha;
private javax.swing.JFormattedTextField campotel1;
private javax.swing.JFormattedTextField campotel2;
private javax.swing.JTextField campousu;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
// End of variables declaration
}
esse código está dando erro mano
Prezado, escuta seus colegas do fórum e implementa a verificação do CPF dentro do método cadastrarusuario
de sua classe DAO
.
E por favor, quando postar código no fórum, formata ele usando o botão </>
, pois do jeito que está é muito ruim de ler e copiar.
Vamos lá. De fato eu errei em alguns pontos…
altere essas partes…
if (usuario.getNome().equals(" “) || usuario.getCpf().equals(” “) || usuario.getEndereco().equals(” “) || usuario.getTel1().equals(” “) || usuario.getEmail().equals(” “) || usuario.getUsuario().equals(” “) || usuario.getSenha().equals(” ")) {
JOptionPane.showMessageDialog(null, “Os campos não podem retornar vazios!”, “Atenção”, JOptionPane.WARNING_MESSAGE);
}
pst = conexao.prepareStatement(“select cpf from usuarios where cpf = ?;”);
pst.setString(1, usuario.getCpf());
rs = pst.executeQuery();
if(rs.next()){
String cpf = rs.getString(1);
if(cpf.equals(usuario.getCpf())){
JOptionPane.showMessageDialog(null, “O CPF JÁ ESTÁ CADASTRADO!”);
}
}
Verifique novamente…
nada ainda guerreiro
minha classe DAO é essa.
package DAO;
import java.sql.*;
import ping.Usuario;
import factory.moduloconexao;
public class UsuarioDAO {
private Connection connection;
String nome,cpf,endereco,tel1,tel2,email;
String usuario;
String senha;
String perfil;
Connection conexao = null;
PreparedStatement pst = null;
ResultSet rs = null;
public void cadastrarusuario(Usuario Usuario){
String sql = "INSERT INTO usuarios(nome,cpf,endereco,tel1,tel2,email,perfil,usuario,senha) VALUES(?,?,?,?,?,?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, Usuario.getNome());
stmt.setString(2, Usuario.getCpf());
stmt.setString(3, Usuario.getEndereco());
stmt.setString(4, Usuario.getTel1());
stmt.setString(5, Usuario.getTel2());
stmt.setString(6, Usuario.getEmail());
stmt.setString(7, Usuario.getPerfil());
stmt.setString(8, Usuario.getUsuario());
stmt.setString(9, Usuario.getSenha());
stmt.execute();
} catch (SQLException u) {
throw new RuntimeException(u);
}
}
public UsuarioDAO(){
this.connection = new moduloconexao().conector();
}
}
A parte que faz a verificação se o CPF está cadastrado ou não é essa
pst = conexao.prepareStatement(“select cpf from usuarios where cpf = ?;”);
pst.setString(1, usuario.getCpf());
rs = pst.executeQuery();
if(rs.next()){
String cpf = rs.getString(1);
if(cpf.equals(usuario.getCpf())){
JOptionPane.showMessageDialog(null, “O CPF JÁ ESTÁ CADASTRADO!”);
}
}
Não tem erro.
private boolean jaExiste() {
try {
String sql = "SELECT cpf FROM usuarios WHERE cpf like ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, usuario.getCpf());
ResultSet result = stmt.executeQuery();
return result.next();
} catch (SQLException u) {
throw new RuntimeException(u);
}
return false;
}
public void cadastrarUsuario(Usuario usuario){
if (jaExiste(usuario)) {
throw new UsuarioJaExisteException();
}
try {
String sql = "INSERT INTO usuarios (nome, cpf, endereco, tel1, tel2, email, perfil, usuario, senha) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, usuario.getNome());
stmt.setString(2, usuario.getCpf());
stmt.setString(3, usuario.getEndereco());
stmt.setString(4, usuario.getTel1());
stmt.setString(5, usuario.getTel2());
stmt.setString(6, usuario.getEmail());
stmt.setString(7, usuario.getPerfil());
stmt.setString(8, usuario.getUsuario());
stmt.setString(9, usuario.getSenha());
stmt.executeUpdate();
} catch (SQLException u) {
throw new RuntimeException(u);
}
}