Errore java.langNullpointer exception

di il
8 risposte

Errore java.langNullpointer exception

Ciao a tutti
sto scrivendo un programma per un esame universitario. si tratta dell'inserimenti dei dati in una jtable. Dopo aver eliminato ogni possibile errore faccio il run ed è tutto apposto ma dopo che ho inserito i valori e schiaccio save... mi esce il seguente errore in una finestra:

Java.lang.null pointer exception
vi scrivo il programma perche non riesco a capire dove sia il problema.. grazie a tutti quelli che mi aiuteranno...


package gestionepiant;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author sp
 */
public class NewJFrame1 extends javax.swing.JFrame {
    private Object con;
    Connection conn=null;
    PreparedStatement pst=null;

    /**
     * Creates new form NewJFrame1
     */
    @SuppressWarnings({"unchecked", "empty-statement", "unchecked", "unchecked"})
    public NewJFrame1() throws ClassNotFoundException {
        try {
            initComponents();
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/gestionepiante","root","admin");
            Statement state =conn.createStatement();
            ResultSet rs=state.executeQuery("SELECT * FROM piante");
           
        ResultSetMetaData rsmetadata=rs.getMetaData();
        int columns=rsmetadata.getColumnCount();
       
        
        DefaultTableModel dtm= new DefaultTableModel();
        Vector columns_name=new Vector();
        Vector data_rows=new Vector();
        
        for(int i=1; i<=columns;i++)
        {
            columns_name.addElement(rsmetadata.getColumnName(i));    
        }
        
       dtm.setColumnIdentifiers(columns_name);
        
       while(rs.next()){
         data_rows=new Vector();
         for(int j=1;j<=columns;j++)
         {
             data_rows.addElement(rs.getString(j));  
         }
         dtm.addRow(data_rows);
        }
         myTable1.setModel(dtm);
  
        } catch (SQLException ex) {
            Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        myTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        cmd_save = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        myTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
            }
        ));
        jScrollPane1.setViewportView(myTable1);

        jLabel1.setBackground(new java.awt.Color(255, 255, 255));
        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Query gestione piante");

        jLabel2.setText("nome_botanico");

        jLabel3.setText("nome_comune");

        jLabel4.setText("giardino");

        jLabel5.setText("esotica");

        jLabel6.setText("prezzo");

        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jTextField4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField4ActionPerformed(evt);
            }
        });

        cmd_save.setText("SAVE");
        cmd_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmd_saveActionPerformed(evt);
            }
        });

        jLabel7.setText("codice_p");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(91, 91, 91))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField2)
                            .addComponent(jTextField3)
                            .addComponent(jTextField4)
                            .addComponent(jTextField5)
                            .addComponent(jTextField6))))
                .addGap(18, 18, 18)
                .addComponent(cmd_save, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(68, 68, 68)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmd_save))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17))
        );

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

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void cmd_saveActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
          String sql="Insert into piante(codice_p,nome_botanico,nome_comune,giardino, esotica,prezzo) value(?,?,?,?,?,?)" ;
                   pst=conn.prepareStatement(sql);
        pst.setString(1,jTextField1.getText());
        pst.setString(2, jTextField2.getText());
        pst.setString(3, jTextField3.getText());
        pst.setString(4, jTextField4.getText());
        pst.setString(5, jTextField5.getText());
         pst.setString(6,jTextField6.getText());
        
       pst.execute();
          JOptionPane.showMessageDialog(null,"Saved");
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null,e);
    }                                        
}

    /**
     * @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(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame1.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() {
                try {
                    new NewJFrame1().setVisible(true);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton cmd_save;
    private javax.swing.JLabel jLabel1;
    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.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTable myTable1;
    // End of variables declaration                   
}


8 Risposte

  • Re: Errore java.langNullpointer exception

    luigi83 ha scritto:


    Java.lang.null pointer exception
    vi scrivo il programma perche non riesco a capire dove sia il problema.. grazie a tutti quelli che mi aiuteranno...
    Premesso che quando vedo del codice come quello che hai postato mi passa quasi la voglia di rispondere sui forum .....

    Comunque tecnicamente il problema del NullPointerException è sicuramente dovuto alla variabile 'conn'. Hai messo una variabile di istanza

    Connection conn=null;

    Ma poi nel costruttore hai dichiarato una nuova variabile

    Connection conn =DriverManager.getConnection( ........

    In pratica non stai assegnando alla variabile di istanza. Quindi resta a null e pertanto nel cmd_saveActionPerformed hai il NullPointerException quando cerchi di invocare conn.prepareStatement(sql).
  • Re: Errore java.langNullpointer exception

    Grazie mille e come lo dovrei modificare il codice per risolvere il problema?
  • Re: Errore java.langNullpointer exception

    luigi83 ha scritto:


    grazie mille e come lo dovrei modificare il codice per risolvere il problema?
    Assegna alla variabile di istanza .... non ad una locale al costruttore.
  • Re: Errore java.langNullpointer exception

    Non capisco... mi da sempre lo stesso errore chi mi aiuta scrivendomi il codice corretto?
    GRazie
  • Re: Errore java.langNullpointer exception

    luigi83 ha scritto:


    Non capisco... mi da sempre lo stesso errore chi mi aiuta scrivendomi il codice corretto?
    GRazie
    Hai tolto la definizione della variabile 'conn' dal costruttore di NewJFrame1? Se l'hai fatto e hai un altro errore, precisa bene quale, dove e se non vuoi ripostare il codice, almeno descrivi quale è la riga incriminata.
  • Re: Errore java.langNullpointer exception

    Ho fatto cosi...togliendo il conn:
    public class NewJFrame1 extends javax.swing.JFrame {
        private Object con;
        Connection conn=null;
        PreparedStatement pst=null;
    
        /**
         * Creates new form NewJFrame1
         */
        @SuppressWarnings({"unchecked", "empty-statement", "unchecked", "unchecked"})
        public NewJFrame1() throws ClassNotFoundException {
            try {
                initComponents();
                Class.forName("com.mysql.jdbc.Driver");
                Connection dbs=DriverManager.getConnection("jdbc:mysql://localhost:3306/gestionepiante","root","admin");
                Statement state =conn.createStatement();
                ResultSet rs=state.executeQuery("SELECT * FROM piante");
    ma mi da errore.. qui
    Statement state =conn.createStatement();
    perche?
  • Re: Errore java.langNullpointer exception

    luigi83 ha scritto:


    Ho fatto cosi...togliendo il conn:
    ma mi da errore.. qui
    Statement state =conn.createStatement();
    perche?
    Tra il tuo codice iniziale:
    Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/gestionepiante","root","admin");
    Statement state =conn.createStatement();
    e il tuo ultimo codice:
    Connection dbs=DriverManager.getConnction("jdbc:mysql://localhost:3306/gestionepiante","root","admin");
    Statement state =conn.createStatement();
    Che differenza c'è (a parte es. spaziature) ??

    Che hai sempre una variabile locale, in precedenza chiamata 'conn' e poi ora 'dbs'. Io ti avevo detto, e lo ripeto ancora: non devi definire una nuova variabile! Devi assegnare alla variabile di istanza chiamata conn!!

    Quindi solo:

    conn = DriverManager. ...........
  • Re: Errore java.langNullpointer exception

    Grazie mille risolto e funzionante
Devi accedere o registrarti per scrivere nel forum
8 risposte