Problem mit ResultSet und ResultSet.next

Hallo :smiley:

Ich bin Einstieger was Java betrifft und versuche mich aktuell an Java in Verbindung mit Datenbanken. Für die Berufsschule möchte ich in den Ferien schonmal bisschen vorarbeiten zudem mich das Thema mit den Datenbanken sehr interessiert. Das Ganze mache ich Stück für Stück nach folgender Anleitung:

http://www.homeandlearn.co.uk/java/database_scrolling_buttons.html

Das ist auch direkt der Link zu dem Teil an dem ich hängen bleibe. Ich möchte jetzt mittels der Funktion rs.next (ResultSet.next) zum nächsten Datenbankeintrag springen. Kompilieren kann ich den ganzen Krma ohne Probleme, wenn ich dann jedoch den entsprechenden Button anklicke, kommt die ultimative Fehlermeldungsflut. Ich habe den ganzen Quelltext schon durchgeschaut und nach Fehlern gesucht, kann allerdings nichts finden.

Vielleicht könnt ihr mir helfen? :o

PS: So eine Spoilerfunktion wäre im Forum hier vielleicht ganz gut. Könnte man lange Texte in Spoiler verpacken un die Sache dadurch ein bisschen übersichtlicher machen.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at Patienten.Patienten.btnNextActionPerformed(Patienten.java:238)
	at Patienten.Patienten.access$300(Patienten.java:16)
	at Patienten.Patienten$4.actionPerformed(Patienten.java:126)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
	at java.awt.Component.processMouseEvent(Component.java:6505)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
	at java.awt.Component.processEvent(Component.java:6270)
	at java.awt.Container.processEvent(Container.java:2229)
	at java.awt.Component.dispatchEventImpl(Component.java:4861)
	at java.awt.Container.dispatchEventImpl(Container.java:2287)
	at java.awt.Component.dispatchEvent(Component.java:4687)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
	at java.awt.Container.dispatchEventImpl(Container.java:2273)
	at java.awt.Window.dispatchEventImpl(Window.java:2719)
	at java.awt.Component.dispatchEvent(Component.java:4687)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
	at java.awt.EventQueue.access$200(EventQueue.java:103)
	at java.awt.EventQueue$3.run(EventQueue.java:688)
	at java.awt.EventQueue$3.run(EventQueue.java:686)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
	at java.awt.EventQueue$4.run(EventQueue.java:702)
	at java.awt.EventQueue$4.run(EventQueue.java:700)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

Hier mein Quelltext für den Button:

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
         try    {
           if (rs.next()) {
               // rs.next( );
                
            int id_col = rs.getInt("ID");
            String id = Integer.toString(id_col);
            String first_name = rs.getString("First_Name");
            String last_name = rs.getString("Last_Name");
            String title = rs.getString("Title");

                    textID.setText(id);
                    textFirstName.setText(first_name);
                    textLastName.setText(last_name);
                    textJobTitle.setText(title);
                }
            else {
                rs.previous( );
                JOptionPane.showMessageDialog(Patienten.this, "End of File");
                }
                } 
         catch (SQLException err) {
                JOptionPane.showMessageDialog(Patienten.this, err.getMessage());
                }
    }                                       

Hi,

wie wärs mit etwas mehr Quellcode? Ist so doch etwas schwer ersichtlich wo es knallt.
Hast du vorher auch eine Datenbankabfrage die das ResultSet “füllt”?
In welcher zeile von deinem **geposteten **Code ist denn die NPE?
Oder hast du jetzt nur diesen part copy&paste ?

nen Spoiler bekommst du über
Guckst du da
[spoiler]http://forum.byte-welt.net/showthread.php?t=4813&highlight=Spoiler[/spoiler]

Wenn du den Code noch in `````` Tags postest (kannst du oben in der Combobox “–Code–” neben der # auswählen) stehen da sogar Zeilennummern daneben und dein Code wird bunt.

at Patienten.Patienten.btnNextActionPerformed(Patienten.java:238)

Gut gelesen, die NullPointerException fliegt tatsächlich in der Methode “btnNextActionPerformed”. Die genaue Zeile ist 238. Was ist die 238 in dem von dir geposteten Code?

Zeile 238:

if (rs.next()) {

Weiter oben in der Datei wird die Verbindung zur Datenbank hergestellt und die Zeilen ausgelesen:


            Statement stmt = con.createStatement( );
            String sql = "SELECT * FROM Patienten";
            ResultSet rs = stmt.executeQuery(sql);```

dann ist der Fehler klar:
dein ResultSet ist leer bzw. null

Wenn du uns mal die ganze Klasse zeigts können wir dir auch sagen warum.

Edit:

Im Tutorial von dir sind

Statement stmt;
ResultSet rs;```
als Klassenvariablen definiert.
Ist das bei dir auch so?
Wenn nein könnte es da dran schon liegen.

Danke soweit erstmal, hier die komplette Klasse:

Komplette Klasse
[spoiler]

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Patienten;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
 *
 * @author Maltris
 */
public class Patienten extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs;
    
    /**
     * Creates new form Patienten
     */
    public Patienten() {
        initComponents();
        DoConnect();
    }
    
    public void DoConnect( ) {
        try {
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java", "user", "pass");

            Statement stmt = con.createStatement( );
            String sql = "SELECT * FROM Patienten";
            ResultSet rs = stmt.executeQuery(sql);
        ////////
        //Schleife um alle Datensätze in cli auszugeben
        //while (rs.next()) {
        ///////
        rs.next();
            int id_col = rs.getInt("ID");
            String id = Integer.toString(id_col);
            String first_name = rs.getString("First_Name");
            String last_name = rs.getString("Last_Name");
            String title = rs.getString("Title");
            
            ////////
            //Gibt alle Zeilen der Datenbank aus
            //String p = id_col + " " + first_name " " + last_name + " " + title;
            //System.out.println(id_col + " " + first_name + " " + last_name + " " + title);
            ////////
            
            //Füllt das Formular mit der ersten Zeile der Datenbank
            textID.setText(id);
            textFirstName.setText(first_name);
            textLastName.setText(last_name);
            textJobTitle.setText(title);
        ////////
        //Ende der Schleife um alle Datensätze auszugeben
        //}    
        ////////
           
        }
            catch (SQLException err) {
                System.out.println(err.getMessage( ));
        }
    }

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

        jPanel1 = new javax.swing.JPanel();
        textFirstName = new javax.swing.JTextField();
        textID = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        textLastName = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        btnFirst = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();
        btnPrevious = new javax.swing.JButton();
        textJobTitle = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

        jLabel1.setText("ID:");

        jLabel2.setText("Name:");

        jLabel3.setText("Nachname:");

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

        jLabel4.setText("Titel:");

        btnFirst.setText("Erster");

        btnNext.setText("Weiter");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnLast.setText("Letzter");

        btnPrevious.setText("Zurück");

        textJobTitle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textJobTitleActionPerformed(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(34, 34, 34)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(78, 78, 78)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(textID, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textLastName, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textJobTitle, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(61, 61, 61)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnFirst)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnLast))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnNext)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnPrevious)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(btnFirst)
                    .addComponent(btnLast))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(btnNext)
                    .addComponent(btnPrevious))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textJobTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        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)
                .addGap(0, 115, Short.MAX_VALUE))
        );

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

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

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

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

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

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
         try    {
           if (rs.next()) {
               // rs.next( );
                    //Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java", "user", "pass");
                
            int id_col = rs.getInt("ID");
            String id = Integer.toString(id_col);
            String first_name = rs.getString("First_Name");
            String last_name = rs.getString("Last_Name");
            String title = rs.getString("Title");

                    textID.setText(id);
                    textFirstName.setText(first_name);
                    textLastName.setText(last_name);
                    textJobTitle.setText(title);
                }
            else {
                rs.previous( );
                JOptionPane.showMessageDialog(Patienten.this, "End of File");
                }
                } 
         catch (SQLException err) {
                JOptionPane.showMessageDialog(Patienten.this, err.getMessage());
                }
    }                                       

    /**
     * @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(Patienten.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Patienten.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Patienten.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Patienten.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 Patienten().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton btnFirst;
    private javax.swing.JButton btnLast;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textFirstName;
    private javax.swing.JTextField textID;
    private javax.swing.JTextField textJobTitle;
    private javax.swing.JTextField textLastName;
    // End of variables declaration                   
}

[/spoiler]

Alle Variablen, die du als Instanzvariablen deklariert hast, hast du auch in der Methode doConnect nochmal unter selbem Namen deklariert. Dadurch werden innerhalb dieser Methode DIESE Variablen verwendet und nicht wie gewünscht die Instanzvariablen.
Beispiel ResultSet rs: In doConnect Du machst das hier:

// Variable rs als methodenlokale Variable neu deklrariert
// und initialisiert
ResultSet rs = stmt.executeQuery(sql);```
D.h. Du weist den Wert einer Variablen zu, die direkt in der Methode deklariert und deswegen auch nur dort gültig ist. Probiers mal so:

// So wird die Instanzvariable verwendet
rs = stmt.executeQuery(sql);

Ich bin ja ein Bob. Das stand sogar genau so im Tutorial.

Wieder ein bisschen schlauer. :slight_smile: Danke erstmal.