views:

334

answers:

4

I have created a class which name is Manager and I have a Frame which name is BirthList and this frame has a table.I work with MySQL and I have entered some data in the "birthtable" in MySQL.and i want to add those data from MySQL table in to the table which is in my frame . HINT: birthList is a list of Birth objects. but I will find this exception why? Please help me:(

Manager class:

  public Manager class{
  Logger logger = Logger.getLogger(this.getClass().getName());
  private static Connection conn = DBManager.getConnection();
  private static Admin admin;

  public static void addToBirthListFromMySQL() throws SQLException {



    try{
      Statement  stmt = conn.createStatement();



     ResultSet rs= stmt.executeQuery("SELECT * FROM birthtable");

       Birth list1;

        while (rs.next()) {
            String s1 = rs.getString(2);
            if (rs.wasNull()) {
                s1 = null;
            }
            String s2 = rs.getString(3);
            if (rs.wasNull()) {
                s2 = null;
            }
            String s3 = rs.getString(4);
            if (rs.wasNull()) {
                s3 = null;
            }
            String s4 = rs.getString(5);
            if (rs.wasNull()) {
                s4 = null;
            }
            String s5 = rs.getString(6);
            if (rs.wasNull()) {
                s5 = null;
            }
            String s6 = rs.getString(7);
            if (rs.wasNull()) {
                s6 = null;
            }


          list1 = new Birth(s1, s2, s3, s4, s5, s6);
          admin.birthList.add(list1);


        }




    }
    catch(SQLException e){





    }

}

My Frame:

public class BirthList extends javax.swing.JFrame {

    private Admin admin;

    /** Creates new form BirthList */
    public BirthList(Admin admin) {
        initComponents();
        this.admin = admin;
        try {
            Manager.addToBirthListFromMySQL();
        } catch (SQLException ex) {
            Logger.getLogger(BirthList.class.getName()).log(Level.SEVERE, null, ex);
        }
        fillTable();
    }


public void fillTable() {

        String[] columNames = {"name", "family", "father's name", "mother's name", "date of birth", "place of birth"};
        List<Birth> birth = admin.getBirthList();
        Object[][] data = new Object[birth.size()][columNames.length];
        for (int i = 0; i < data.length; i++) {
            Birth birth1 = birth.get(i);
            data[i][0] = birth1.getName();
            data[i][1] = birth1.getFamily();
            data[i][2] = birth1.getFatherName();
            data[i][3] = birth1.getMotherName();
            data[i][4] = birth1.getDateOfBirth();
            data[i][5] = birth1.getPlaceOfBirth();


        }
        DefaultTableModel model = new DefaultTableModel(data, columNames);
        jTable1.setModel(model);
    }

    public boolean isCellEditable(int row, int col) {
        return true;
    }
}

stacktrace: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at database.Manager.addToBirthListFromMySQL(Manager.java:272) at AdminGUI.BirthList.(BirthList.java:35) at AdminGUI.BirthFrame.newButton1ActionPerformed(BirthFrame.java:127) at AdminGUI.BirthFrame.access$000(BirthFrame.java:21) at AdminGUI.BirthFrame$1.actionPerformed(BirthFrame.java:58) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6038) at javax.swing.JComponent.processMouseEvent(JComponent.java:3265) at java.awt.Component.processEvent(Component.java:5803) at java.awt.Container.processEvent(Container.java:2058) at java.awt.Component.dispatchEventImpl(Component.java:4410) at java.awt.Container.dispatchEventImpl(Container.java:2116) at java.awt.Component.dispatchEvent(Component.java:4240) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916) at java.awt.Container.dispatchEventImpl(Container.java:2102) at java.awt.Window.dispatchEventImpl(Window.java:2429) at java.awt.Component.dispatchEvent(Component.java:4240) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160) at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

line 272 is :admin.birthList.add(list1);

**I also debug my project and the result was :

debug: Listening on javadebug User program running Debugger stopped on uncompilable source code.

*I also print my object admin with system.out.println(admin) and the result was:

classes.Admin@20be79*

A: 

It's hard to tell because the line numbers in the stack trace don't seem to match your code, but do you ever set the "private static Admin admin;" variable in Manager to a non-null value?

Ash
+2  A: 

At first glance, I would say your Admin instance is null, causing the NPE in the addToBirthListFromMySQL() method

public BirthList(Admin admin) {
        initComponents(); // where do you set this.admin to the parameter 'admin' ?

You also need to initialize the static variable admin of your static object Manager

public BirthList(Admin admin) {
        this.admin = admin
        Manager.admin = admin
        initComponents();

(note: you may want to not call your parameter with the same name than internal variables)


I also debug my project and the result was :

debug: Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\lib\sunrsasign.jar

Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\classes**

Make sure you are not using the 1.6 compiler and the 1.5 runtime to execute/debug your program.

See this thread:

Here is a list of possibilities for future users:

  1. Committed to the Repository. (probably not)
  2. Re-Set all of my responsible environment variables...
    a. set path="D:\...\JDK1.5\bin"
    b. set classpath="D:\...\JDK1.5\bin"
    c. set java_home="D:\...\JDK1.5"
  3. Re-set all of my Dependencies on my project. (Project Properties->Libraries).
VonC
yes,you are right I added it but still I have that NPE:(
Johanna
sorry .but i didn't get what you mean can you explain more!!!!!
Johanna
+4  A: 

Instead of hunting the root cause in the dark, I think it's better to explain how and why NPE's are caused and how they can be avoided, so that the OP can apply the newly gained knowledge to hunt his/her own trivial problem.

Look, object references (the variables) can contain either a fullworthy Object or simply nothing, which is null.

SomeObject someObject1 = new SomeObject(); // References something.
SomeObject someObject2 = null; // References nothing.

Now, if you're trying to access nothing (null), then you will undoubtely get a NullPointerException, simply because null doesn't have any variables or methods.

someObject1.doSomething(); // Works fine.
someObject2.doSomething(); // Throws NullPointerException.

Workarounding this is fairly simple. It can be done in basically two ways: either by instantiating it or just by ignoring it.

if (someObject2 == null) {
    someObject2 = new SomeObject();
}
someObject2.doSomething(); // No NPE anymore!

or

if (someObject2 != null) {
    someObject2.doSomething(); // No NPE anymore!
}

In case of a NPE, the first line number of the stacktrace points the exact line where the it is been caused. You told literally "line 272 is admin.birthList.add(list1);". This line contains two places where object references are been accessed/invoked (using the dot . operator). The first being admin.birthList and the second being birthList.add(list1). It's up to you to find out if one or both caused the NPE. If it is the first invocation, then admin is simply null. If it is the second invocation, then birthList is simply null. You can fix it by instantiating it with a fullworthy object.

Edit: If you have a hard time in determining the root cause (as turns out from comments), then you need to learn debugging. Run a debugger or just do "poor man's debugging" with help of a System.out.println() of every variable before accessing/invoking them. First look at line where the NPE is caused. If this is for example

admin.birthList.add(list1);

then you need to change it as follows to nail down the root cause:

System.out.println("admin: " + admin);
List<Birth> birthList = admin.birthList;
System.out.println("birthList: " + birthList);
birthList.add(list1);

check if any of them prints null. Alternatively you can also do:

if (admin == null) throw new NullPointerException("admin is null!");
List<Birth> birthList = admin.birthList;
if (birthList == null) throw new NullPointerException("birthList is null!");
birthList.add(list1);

you can also separate the individual invocations over separate lines so that you have enough to the line number to know which reference is null.

List<Birth> birthList = admin.birthList; // If NPE line points here, then admin is null.
birthList.add(list1); // If NPE line points here, then birthList is null.
BalusC
I have done what ever you told me but I still have NPE:(((((((((
Johanna
also i found that my birthList is null not my admin object ,also I have done if(admin==null birthList = new ArrayList<Birth>(); } else{ admin.birthList.add(list1); }but still I have NPE:((((((((
Johanna
Then learn debugging. I've edited my answer with more help.
BalusC
+1 for the effort, the details about NPE and for the "Then learn debugging" comment ;)
VonC
wow,thanks a lot I found that birthList is null and I solve that,thanks a million :">
Johanna
Nice tutorial BalusC !
Steve De Caux
A: 

If line 272 of Manager.java is:

admin.birthList.add(list1);

and if admin is not null which is my understanding of your updates, then the conclusion seems pretty obvious: birthlist is null and the code breaks when you call the add() method on it.

My guess is that your Admin class looks something like this:

public class Admin {
    public List<Birth> birthList; //the visibility seems to be public
    ...
}

and you never initialize the birthList class attribute. So either initialize it inline, in the constructor, in an init() method, etc but do it somewhere. For example, inline:

public class Admin {
    public List<Birth> birthList = new ArrayList<Birth>(); 
    ...
}

Actually, I'm not sure how you instantiate and set the Admin static instance of your Manager class but this is another story.

Pascal Thivent