Mends.One

× 274612 Retrieving and displaying Msql database data on a textarea using a Java application

Swing, Java

I have created a MySQL database with 4 columns.I want to read the second column of the database and display it on a text area. I have method display() that is called when i click on a button. The code for the method is:

public void display(){
    db=new Database();
    try{
        int n=Integer.parseInt(field.getText());

        ResultSet rset=Database.conn.createStatement().executeQuery("select * from mymusic where trackNumber like'"+n+"'");
        while(rset.next()){
            area.setText(rset.getString("Songlocation"));
        }
        rset.close();

    }catch(SQLException e){
        JOptionPane.showMessageDialog(this,"Database error","Warning",JOptionPane.ERROR_MESSAGE);
    }
    catch(NumberFormatException numfom)
    {
        JOptionPane.showMessageDialog(this,"Invalid Entry","Warning",JOptionPane.ERROR_MESSAGE);
    }

}

A Exception in thread "AWT-EventQueue-0" java.Lang.NullPointerException is thrown when i execute the code and of cos no display. The database connection is perfect since i can update the database successfully. assist me print the data on the text-area.

0
U
user1549866
Jump to: Answer 1

Answers (1)

Without the full stack trace it is hard to determine what exactly caused the NullPointerException.

Looking at the source code the Integer.parseInt will not throw a NullPointerException when passing null, and the JTextArea#setText can handle a null value as well.

The remaining candidates: field can be null, rset can be null (unlikely as that would trigger NPE's at other locations in the code), area can be null . Should be pretty straight-forward to determine when you have the stacktrace or use a debugger.

Next to that, some other advise:

  • You should move your rset.close() statement in a finally block to make sure it gets closed, even when an exception occurs
  • You should not query the database on the Event Dispatch Thread. Use a worker thread instead. Database access is a slow operation, which will result in a blocked UI until the query is completed. See the Concurrency in Swing tutorial for more information
1
R
Robin

Related Questions