Error: java.lang.Nullpointerexception in project using JDBC

Asked

Viewed 518 times

0

Could help me with the error below, it is a, I have error in lines 14 of the class Testalista and error in line 32 of the class ContatoDao.

Exception in thread "main" java.lang.NullPointerException
    at br.com.caelum.jdbc.dao.ContatoDao.getLista(ContatoDao.java:28)
    at br.com.caelum.jdbc.teste.TestaLista.main(TestaLista.java:14)

Class TestaLista:

public class TestaLista {
    public static void main(String[] args) throws RuntimeException{

        ContatoDao dao = new ContatoDao();
        List<Contato> contatos = dao.getLista(); // <-- Aponta erro nessa parte

        for(Contato contato : contatos) {
            System.out.println("Nome: " + contato.getNome());
            System.out.println("Email: " + contato.getEmail());
            System.out.println("Endereço: " + contato.getEndereco());
            System.out.println("Data de Nascimento: " + 
                            contato.getDataNascimento().getTime() + "\n") ;
        }
    }
}

Class ContatoDao, with error in the PreparedStatement:

public class ContatoDao {
    private Connection connection;

    public void adiciona(Contato contato) {
        String sql = "insert into contatos" + 
                "(nome, email, endereco, dataNascimento)" + 
                "values(?,?,?,?)";  
    }

    public List<Contato> getLista(){
        try {
            List<Contato> contatos = new ArrayList<Contato>();
            PreparedStatement stmt = this.connection
                    .prepareStatement("select * from contatos"); // <-- Aponta erro nessa parte...
            ResultSet rs = stmt.executeQuery();

            while(rs.next()) {

                //Objeto contato
                Contato contato = new Contato();
                contato.setId(rs.getLong("id"));
                contato.setNome(rs.getString("nome"));
                contato.setEmail(rs.getString("email"));
                contato.setEndereco(rs.getString("endereco"));

                //montando a data com Calendar
                Calendar data = Calendar.getInstance();
                data.setTime(rs.getDate("dataNascimento"));
                contato.setDataNascimento(data);

                contatos.add(contato);
            }
            rs.close();
            stmt.close();
            return contatos;
        }catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }
}   

Follow the connection classes:

public class ConnectionFactory {
    public Connection getConnection() {
        try {
            return DriverManager.getConnection(
                    "jdbc:mysql://localhost/fj21?useSSL=false", "root", "");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }   
}

Class ConnectionTeste:

public class ConnectionTeste {
    public static void main(String[] args) throws SQLException {

        Connection connection = new ConnectionFactory().getConnection();
        System.out.println("Conexão aberta!");
        connection.close();
    }       
}
  • Your connection may be null, always make sure to start the connection before creating a Statement.

  • Without looking right and even without having enough information I think I can say that the problem is lack of initialization of connection.

  • @Articuno the link you passed helped in some fixes but I still have the same problem :/

  • If you don’t start the connection, the problem will never be solved anyway.

  • See also: https://answall.com/q/172909/132

Show 1 more comment

1 answer

0


Let’s change a detail on your ConnectionFactory:

public class ConnectionFactory {
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(
                    "jdbc:mysql://localhost/fj21?useSSL=false", "root", "");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }   
}

The detail is that modifier static the most.

Now, to your class ConnectionTeste undergoes a change:

public class ConnectionTeste {
    public static void main(String[] args) {
        try (Connection connection = ConnectionFactory.getConnection()) {
            System.out.println("Conexão aberta!");
        }
    }
}

With that, we’ll remake your DAO:

public class ContatoDao {

    private static final String INSERT_SQL = ""
            + "INSERT INTO Contatos"
            + "(nome, email, endereco, dataNascimento)"
            + "VALUES (?, ?, ?, ?)";

    private static final String SELECT_SQL = "SELECT * FROM Contatos";

    public void adiciona(Contato contato) {
        // String sql = INSERT_SQL;  
    }

    public List<Contato> getLista() {
        try (
            Connection c = ConnectionFactory.getConnection();
            PreparedStatement stmt = c.prepareStatement(SELECT_SQL);
            ResultSet rs = stmt.executeQuery();
        ) {
            List<Contato> contatos = new ArrayList<>();
            while (rs.next()) {

                //Objeto contato
                Contato contato = new Contato();
                contato.setId(rs.getLong("id"));
                contato.setNome(rs.getString("nome"));
                contato.setEmail(rs.getString("email"));
                contato.setEndereco(rs.getString("endereco"));

                //montando a data com Calendar
                Calendar data = Calendar.getInstance();
                data.setTime(rs.getDate("dataNascimento"));
                contato.setDataNascimento(data);

                contatos.add(contato);
            }
            return contatos;
        } catch(SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Your class TestaLista remains virtually equal:

public class TestaLista {

    public static void main(String[] args) {
        ContatoDao dao = new ContatoDao();
        List<Contato> contatos = dao.getLista();

        for (Contato contato : contatos) {
            System.out.println("Nome: " + contato.getNome());
            System.out.println("Email: " + contato.getEmail());
            System.out.println("Endereço: " + contato.getEndereco());
            System.out.println("Data de Nascimento: " + 
                    contato.getDataNascimento().getTime() + "\n") ;
        }
    }
}

Note that I used the Try-with-Resources in all cases.

I also recommend using the class LocalDate instead of Calendar to represent dates.

  • Victor Stafusa, got master! thank you so much for your help. So my code error was in the declaration of my SQL code?

  • 1

    @Thiagopernomian No. The error was the field connection in his ContatoDao that was null.

Browser other questions tagged

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