Nullpointerexception error, where is the error?

Asked

Viewed 175 times

2

I wanted to know where the mistake is. I read that the mistake NullPointerException is when we try to access a variable that wasn’t initialized, I just didn’t find this error in my code.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;

/*
 * 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.
 */

/**
 *
 * @author User
 */
public  class NovoJFrame extends javax.swing.JFrame {

     PreparedStatement stl;
     ResultSet rs;
     Connection con;



    public NovoJFrame() {
        initComponents();

        IniciarBD();

        this.PrencherComboBox();

        jPanel3.setVisible(false);
    }


    public void PrencherComboBox(){
        String sql = "Select * from ALUNO";
        try {

               stl = con.prepareStatement(sql);
               rs = stl.executeQuery();

               while(rs.next()){
                   jComboBox1.addItem(rs.getString("NOME"));
               }
           } catch(SQLException ex){
               JOptionPane.showMessageDialog(null,ex);
           }

    }





    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<>();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox<>();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(java.awt.Color.blue);

        jPanel1.setBackground(new java.awt.Color(0, 51, 255));
        jPanel1.setForeground(new java.awt.Color(204, 255, 51));

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/liceu terras.png"))); // NOI18N

        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(265, 265, 265)
                .addComponent(jLabel6)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(33, Short.MAX_VALUE)
                .addComponent(jLabel6)
                .addGap(31, 31, 31))
        );

        jPanel2.setBackground(new java.awt.Color(255, 255, 0));

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton1.setText("Visualizar Tempo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/med grande.png"))); // NOI18N

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel7)
                .addGap(40, 40, 40)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(100, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(61, 61, 61))
        );

        jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("Aluno:");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setText("Quantidade:");

        jComboBox2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton2.setText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 255, 0));
        jLabel5.setText("Com Sucesso");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(0, 255, 0));
        jLabel4.setText("Operação Realizada");

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/simbolo dinheiro.png"))); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addGap(115, 115, 115))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(51, 51, 51))))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addContainerGap(30, Short.MAX_VALUE))
        );

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jButton3.setText("Status");

        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)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(116, 116, 116))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(6, 6, 6))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2)
                            .addComponent(jButton3))
                        .addGap(32, 32, 32)))
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        jPanel3.setVisible(true);
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        med frame = new med();  

        frame.setVisible(true);  
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {         






            java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NovoJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JComboBox<String> jComboBox2;
    private javax.swing.JLabel jLabel1;
    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.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    // End of variables declaration                   


    private void IniciarBD(){

        try {
        Class.forName("org.apache.derby.jdbc.ClientDriver");
    } catch ( ClassNotFoundException e){
            System.out.println("Erro :" + e.getMessage() );
    }

    String url = "jdbc:derby://localhost:1527/bd" ;
    String user = "root" ;
    String pass = "senha" ;


        try {
            Connection con = DriverManager.getConnection( url, user, pass );

            Statement stmt = con.createStatement();

            System.out.println("Conexão Realizada com Sucesso");
        } catch (SQLException e) {
            System.out.println("Erro :" + e.getMessage() );
        }

}
}

Stacktrace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at NovoJFrame.PrencherComboBox(NovoJFrame.java:43)
at NovoJFrame.<init>(NovoJFrame.java:33)
at NovoJFrame$3.run(NovoJFrame.java:280)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
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.awt.EventQueue.dispatchEvent(EventQueue.java:726)
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)
  • 1

    Nor is it possible to reproduce the problem with this code you posted. So, which line is the exception?

  • 1

    Exact. It is necessary to inform the stack trace of the exception, with the line where the error occurs. At first glance, the exception may be due to the variables "con", "jPanel3" or "jComboBox1", which we are not sure if they were initialized. Another thing, your SQL is glued "*" to "from", give a space in the middle of them.

  • "read that the error NullPointerException is when we try to access a variable that has not been initialized" - Not exactly, see more in this my answer. Also, your code is incomplete and you don’t have stacktrace, and because of that you lack essential information in your question so that someone can give a satisfactory answer to it. I ask you to edit the question by adding stacktrace and the rest of your code, including the methods initComponents(), IniciarBD() and PreencherComboBox().

  • What is line 43?

  • @Victorstafusa Ready, changed

  • @Guilhermenascimento stl = con.prepareStatement(sql);

  • has the ability to post the entire Novojframe.java, including the Imports?

Show 2 more comments

2 answers

2

Its main problem is that in the method PreencherComboBox, you do not initialize the connection.

The simplest solution would be to do this:

    public void PrencherComboBox(){
        String sql = "Select * from ALUNO";
        try {
               con = DriverManager.getConnection(url, user, pass);
               stl = con.prepareStatement(sql);
               rs = stl.executeQuery();

               while(rs.next()){
                   jComboBox1.addItem(rs.getString("NOME"));
               }
           } catch(SQLException ex){
               JOptionPane.showMessageDialog(null,ex);
           }

    }

However, since we are here, we can analyze what other problems we have in your code. And there are several of them:

  • You forgot the modifier private in some class attributes. Package visibility is probably not what you want.

  • You open connections, Statements and ResultSetbut it doesn’t close them properly. This is a bad practice that can lead to wasted memory consumption or maintenance of open connections that are no longer useful. The most practical way to deal with this problem is by using the syntax of try so-called Try-with-Resources.

  • You mix visualization logic (swing) with data access logic (JDBC). In order for the code to be organized, it is better to separate it.

  • You are not correctly following the naming conventions of the Java language. Methods must have their name started with lowercase letter.

So let’s solve all these problems:

public class AcessoDados {
    private final String url = "jdbc:derby://localhost:1527/bd";
    private final String user = "root";
    private final String pass = "senha";

    static {
        try {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Erro :" + e.getMessage());
            throw new ExceptionInInitializerError(e);
        }
    }

    public AcessoDados() {
        this.url = "jdbc:derby://localhost:1527/bd";
        this.user = "root";
        this.pass = "senha";
    }

    public AcessoDados(String url, String user, String pass) {
        this.url = url;
        this.user = user;
        this.pass = pass;
    }

    private Connection conectar() {
        return DriverManager.getConnection(url, user, pass);
    }

    public List<String> listarNomesDeAlunos() throws SQLException {
        List<String> lista = new ArrayList<>(10);

        String sql = "SELECT nome FROM ALUNO";
        try (
            Connection con = conectar();
            PreparedStatement stl = con.prepareStatement(sql);
            ResultSet rs = stl.executeQuery();
        ) {
           while (rs.next()) {
               lista.addItem(rs.getString("NOME"));
           }
        }
        return lista;
    }

    public void testarConexao() throws SQLException {
        try (
            Connection con = conectar();
            Statement stmt = con.createStatement();
        ) {
            System.out.println("Conexão Realizada com Sucesso");
        }
    }
}
public class NovoJFrame extends javax.swing.JFrame {

    private final AcessoDados acesso = new AcessoDados();

    public NovoJFrame() {
        initComponents();
        jPanel3.setVisible(false);

        try {
            acesso.testarConexao();
        } catch (SQLException e) {
            System.out.println("Erro :" + e.getMessage());
        }

        this.prencherComboBox();
    }

    public void prencherComboBox() {
        List<String> nomes;
        try {
            nomes = acesso.listarNomesDeAlunos();
       } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, ex);
       }

        for (String nome : nomes) {
            jComboBox1.addItem(nome);
        }
    }

    // ... Resto da classe...
}

There’s still one more serious problem you must solve. You are manipulating the database on the same swing thread. This can make the application non-responsive. The reason is that the database may take a while to request, and during this period, your screen will be frozen. To solve this, try using the class SwingWorker so as not to let the swing crash by doing operations in the database.

However, to propose a solution to this using the SwingWorker, would need to change a lot in the structure of your application, much more than just the snippet of what you posted in the question. Moreover, this subject is already another conversation far removed from the initial purpose of what is outlined in the question. If you are interested, I suggest you ask a new question about this topic.

  • Class.forName("org.apache.derby.jdbc.ClientDriver"); this call is optional if it is using jdk 7+.

  • As a complement to Victor’s answer, here has an example of the use of swingworker with a progress bar. Of course you will need to adapt doInBackground and Publish to your need.

  • @diegofm Yes, but I considered three things: (1) this was already in the original OP code; (2) it is harmless in case the application has no problems with the classpath and report any problems if there are and (3) I answered a question here a few days ago where the OP had managed to mess with this by using an old driver in the classpath. Therefore, I think it best to leave. If the author of the question wants, he can remove the block static { ... } and should/should work in the same way.

  • It’s true, now that I’ve noticed that the code was already like this.

-3

Connection con = null;

stl = con.prepareStatement(sql); // con = null

case IniciarBD() is initiating the variable con, then:

rs = stl.executeQuery();
jComboBox1.addItem(rs.getString("NOME"));

If query execution fails, rs = null.

  • 2

    Friend, it was not I who denied your answer, but I confess that I did not understand exactly what you are proposing that the author of the question.

Browser other questions tagged

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