1
package grid;

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import java.lang.String;

public class ViewData extends JFrame{
   JTable table;
   String rowData[][]=new String[100][100];
    String columnNames[]=new String[3] ;
     static ViewData r;
    public  ViewData() throws ClassNotFoundException, SQLException{
        setLayout(new FlowLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);    

        columnNames[0] ="Name";
        columnNames[1] ="Regno";
        columnNames[2] ="Email";

        r.load();
        table=new JTable(rowData, columnNames);
        add(new JScrollPane(table));
        pack();
    }
   public static void main(String[] args) throws ClassNotFoundException, SQLException {
        r=new ViewData();
    }

     public void load() throws ClassNotFoundException, SQLException{
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/swap_db","swap","swap");
            String q="SELECT * FROM STUDENT";
            Statement stm=con.createStatement();
            ResultSet rs=stm.executeQuery(q);
            int i=0;
            while(rs.next()){
                String name=rs.getString(1);
                String regno=rs.getString(2);
                String email=rs.getString(3);

                rowData[i][0]=name;
                rowData[i][1]=regno;
                rowData[i][2]=email;
                i++;

            }        
        }
}

I am trying to display data in database in JTable but it showing following error.

Exception in thread "main" java.lang.NullPointerException
at grid.ViewData.(ViewData.java:23)
at grid.ViewData.main(ViewData.java:29)
BUILD STOPPED (total time: 5 seconds)

What is error in this program?

1
  • Something is null. Debug your code. Commented Oct 27, 2015 at 14:17

1 Answer 1

3

The following statement invokes the constructor of ViewData;

r=new ViewData();

But inside the constructor, you called:

r.load();

r is null before the constructor returns, that's why it throws a NullPointerException.

So what can do is move r.load() from the constructor to the main method after the instance is created.

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    r=new ViewData();
    r.load();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.