0

I have done a database connection with mysql to eclipse. When executing my code, I get null pointer exception error. This occurs when I click on the Add button to add a new record in the database. Please help

import javax.swing.JFrame;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;

import org.eclipse.wb.swing.FocusTraversalOnArray;

import com.toedter.calendar.JDateChooser;

import java.awt.Component;
import java.awt.BorderLayout;
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

 import javax.swing.JCheckBox;
 import javax.swing.JButton;
 import javax.swing.JTable;
 import javax.swing.JTextField;
 import javax.swing.JComboBox;
 import javax.swing.JRadioButton;
 import javax.swing.DefaultComboBoxModel;

 public class PassF extends JFrame{

private JTextField fname;
private JTextField lname;
private JTextField address;
private JTextField resId;
private JComboBox ori, des;
private JButton btnAdd, btnUpdate, btnDelete, btnClear;
private JRadioButton premium, economy, business;
private JDateChooser dt;



private Connection con;


String url = "jdbc:mysql://localhost:3306/";
String user = "root";
String password = "root";


public PassF(){
    super("Passenger Details");
    setBounds(100, 100, 792, 631);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 831, 78);
    add(panel);

    JLabel l1 = new JLabel();

    l1.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\passenger.png"));
    panel.setBackground(Color.WHITE);
    panel.add(l1);

    JLabel lblFirstName = new JLabel("First Name ");
    lblFirstName.setForeground(new Color(25, 25, 112));
    lblFirstName.setFont(new Font("Candara", Font.BOLD, 15));
    lblFirstName.setBounds(34, 132, 95, 23);
    add(lblFirstName);

    JLabel lblLastName = new JLabel("Last Name ");
    lblLastName.setForeground(new Color(25, 25, 112));
    lblLastName.setFont(new Font("Candara", Font.BOLD, 15));
    lblLastName.setBounds(316, 132, 80, 23);
    add(lblLastName);

    fname = new JTextField();
    setBounds(239, 132, 126, 22);
    add(fname);
    fname.setColumns(10);

    lname = new JTextField();
    lname.setBounds(432, 132, 126, 22);
    add(lname);
    lname.setColumns(10);

    JLabel lblAddress = new JLabel("Address");
    lblAddress.setForeground(new Color(25, 25, 112));
    lblAddress.setFont(new Font("Candara", Font.BOLD, 15));
    lblAddress.setBounds(34, 177, 95, 23);
    add(lblAddress);

    address = new JTextField();
    address.setBounds(139, 178, 126, 56);
    add(address);
    address.setColumns(10);

    JLabel lblReservationId = new JLabel("Reservation ID");
    lblReservationId.setForeground(new Color(25, 25, 112));
    lblReservationId.setFont(new Font("Candara", Font.BOLD, 15));
    lblReservationId.setBounds(316, 173, 107, 31);
    add(lblReservationId);

    resId = new JTextField();
    resId.setBounds(432, 178, 126, 22);
    add(resId);
    resId.setColumns(10);

    JLabel origin= new JLabel("Origin");
    origin.setForeground(new Color(25, 25, 112));
    origin.setFont(new Font("Candara", Font.BOLD, 15));
    origin.setBounds(34, 273, 95, 23);
    add(origin);

    JLabel lblDestination = new JLabel("Destination");
    lblDestination.setForeground(new Color(25, 25, 112));
    lblDestination.setFont(new Font("Candara", Font.BOLD, 15));
    lblDestination.setBounds(34, 316, 95, 23);
    add(lblDestination);

    ori = new JComboBox();
    ori.setModel(new DefaultComboBoxModel(new String[] {"Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Bangladesh", "Barbados", "Belarus", "Belgium", "Brazil", "China", "Egypt", "France", "Germany", "Hong Kong", "India", "Maldives", "Madagascar", "Mauritius", "Nigeria ", "Russia", "Seychelles", "Singapore ", "United Arab Emirates"}));
    ori.setBounds(139, 273, 126, 22);
    add(ori);

    des = new JComboBox();
    des.setModel(new DefaultComboBoxModel(new String[] {"Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Bangladesh", "Barbados", "Belarus", "Belgium", "Brazil", "China", "Egypt", "France", "Germany", "Hong Kong", "India", "Maldives", "Madagascar", "Mauritius", "Nigeria ", "Russia", "Seychelles", "Singapore ", "United Arab Emirates"}));
    des.setBounds(139, 317, 126, 22);
    add(des);

    JLabel clas = new JLabel();
    clas.setForeground(new Color(25, 25, 112));
    clas.setBounds(316, 231, 246, 132);
    clas.setBorder(BorderFactory.createTitledBorder(null, "Class", TitledBorder.LEFT, TitledBorder.TOP, new Font("Candara", Font.BOLD, 15), new Color(25, 25, 112)));
    add(clas);

    ButtonGroup group = new ButtonGroup();

    premium = new JRadioButton("Premium");
    premium.setBounds(338, 257, 109, 23);
    premium.setForeground(new Color(25, 25, 112));
    premium.setFont(new Font("Candara", Font.BOLD, 15));
    group.add(premium);
    add(premium);

    economy = new JRadioButton("Economy");
    economy.setBounds(338, 291, 109, 23);
    add(economy);
    economy.setForeground(new Color(25, 25, 112));
    economy.setFont(new Font("Candara", Font.BOLD, 15));
    group.add(economy);
    add(economy);

    business = new JRadioButton("Business");
    business.setBounds(338, 324, 109, 23);
    business.setForeground(new Color(25, 25, 112));
    business.setFont(new Font("Candara", Font.BOLD, 15));
    group.add(business);
    add(business);

    JLabel lblJourneyDate = new JLabel("Journey Date");
    lblJourneyDate.setForeground(new Color(25, 25, 112));
    lblJourneyDate.setFont(new Font("Candara", Font.BOLD, 15));
    lblJourneyDate.setBounds(34, 90, 95, 22);
    add(lblJourneyDate);



    btnAdd = new JButton();
    btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            insert();
        }
    });

    btnAdd.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\Icons\\add.jpg"));
    btnAdd.setForeground(new Color(34, 139, 34));
    btnAdd.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 15));
    btnAdd.setBounds(647, 143, 85, 31);
    add(btnAdd);


    JButton btnSave = new JButton();
    btnSave.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\Icons\\clear.jpg"));
    btnSave.setForeground(new Color(34, 139, 34));
    btnSave.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 15));
    btnSave.setBounds(647, 203, 85, 31);
    add(btnSave);

    JButton btnUpdate = new JButton();
    btnUpdate.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\Icons\\update.jpg"));
    btnUpdate.setForeground(new Color(34, 139, 34));
    btnUpdate.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 15));
    btnUpdate.setBounds(647, 257, 85, 31);
    add(btnUpdate);

    JButton btnDelete = new JButton("");
    btnDelete.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\Icons\\delete.jpg"));
    btnDelete.setForeground(new Color(34, 139, 34));
    btnDelete.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 15));
    btnDelete.setBounds(647, 317, 80, 31);
    add(btnDelete);

    dt = new JDateChooser();
    dt.setBounds(139, 89, 126, 23);
    add(dt);


    JLabel l2 = new JLabel();
    l2.setBounds(0, 75, 831, 547);
    add(l2);
    l2.setIcon(new ImageIcon("C:\\Users\\Yetin\\workspace\\Assignment\\src\\world.jpg"));




}




    public void insert(){
        try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con  = DriverManager.getConnection(url, user, password);

        System.out.println("Database connection succesful to: " + url);

        }catch(Exception e){
            System.out.println("Error in connecting");
        }


        try{
        PreparedStatement stmt = con.prepareStatement("insert into passenger"
                    + " (ReservID, JourneyDate, FirstName, LastName, Address, ClassType, Origin, Destination)"
                    + " values (?, ?, ?, ?, ?, ?, ?, ?");

            //set parameters

            stmt.setString(1, resId.getText());
            stmt.setString(2, dt.getDateFormatString());
            stmt.setString(3, fname.getText());
            stmt.setString(4, lname.getText());
            stmt.setString(5, address.getText());
            stmt.setString(6, premium.getText());
            stmt.setString(7, ori.getSelectedItem().toString());
            stmt.setString(8, des.getSelectedItem().toString());

            //execute SQL

            stmt.executeUpdate();

        }catch(Exception e){
                System.out.println("ERROR");
            }
    }   
}
yetin
  • 61
  • 11

2 Answers2

2

So what I found through reading your code.. your problem is here ..

 try{
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con  = DriverManager.getConnection(url, user, password);

        System.out.println("Database connection succesful to: " + url);

        }catch(Exception e){
            System.out.println("Error in connecting");
        }

You don't rethrow your exception so it is swallowed. st is then null. Change this to

catch(Exception exp){
    throw new Exception(exp);
}

then you will get the exact reason or the problem which exists with the jdbc connection. Probably missing jars, wrong path or authenitication issue .. may be soemthing else too but you need to first know the reason..
EDIT: I think it may be printing "Error in connecting".. Also there is no point in going ahead with PreparedStatement if connection failed to establish.

Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
  • My DAO codes: pastebin.com/fDeTX7Fu My PassengerForm (Main) pastebin.com/cBSLjyr3 My Passenger Class pastebin.com/v6PdvgkJ The errors I am getting are: Caused by: java.lang.NullPointerException at PassengerForm.saveEmployee(PassengerForm.java:275) ... 37 more – yetin Apr 04 '15 at 13:04
  • @yetin thats exactly what I am saying.. Your con = DriverManager.getConnection(url, user, password); statement is failing to establish the connection..now we have to see why is failing.. – Viraj Nalawade Apr 04 '15 at 13:09
  • But it says database connection succesful ! This line System.out.println("Database connection succesful to: " + url); executes. – yetin Apr 04 '15 at 13:15
  • @yetin thanks.. ok.. That makes me think if private PassengerDAO test; is initialized correctly?? as You also have PassengerForm window = new PassengerForm(); this line where you dont initialize test?? – Viraj Nalawade Apr 04 '15 at 13:25
  • @yetin please let me know as I think this is exactly the problem.. PassengerDAO dao = new PassengerDAO(); is used no where.. try doing PassengerForm window = new PassengerForm(dao ); and see if this works.. – Viraj Nalawade Apr 04 '15 at 13:28
  • Should I include the name of the database in the url ? – yetin Apr 04 '15 at 18:25
  • @yetin Yes you should.. example of URL "jdbc:mysql://localhost/DATABASE_NAME" & then you can just DriverManager.getConnection(URL,USERNAME,PASSWORD); to get connection.. Please correct line 8 of PassengerDAO class..Add a db name.. But also rectify the way you are creating PassengerForm object at line 59 of PassengerForm class..it is wrong there.. change below PassengerForm window = new PassengerForm(); PassengerDAO dao = new PassengerDAO(); To this: PassengerDAO dao = new PassengerDAO(); PassengerForm window = new PassengerForm(dao); Thats it you will move ahead with this much.. – Viraj Nalawade Apr 05 '15 at 05:43
  • Yes man ! It works now. Thank you loads. Also, I forgot to add the database name in the url :/ Thanks again. Btw, can I create a navigation system which have 4 buttons (First, Next, Previous, Last) on my GUI operating with JCombobox and Radiobuttons ? – yetin Apr 05 '15 at 11:25
  • @yetin I am glad it worked ..Yes you can create the navigation system that way but you can also have a look at this http://stackoverflow.com/questions/10901352/navigating-between-multiple-panels .. Also if the answer/comments were helpful could you please accept the answer?? – Viraj Nalawade Apr 05 '15 at 11:33
  • I am unable to vote it up since I am a newbie here :p However, I have marked it right answer (Y) – yetin Apr 05 '15 at 11:43
  • @yetin thank you..Its a helpful place here hope you keep posting questions and answers here.. – Viraj Nalawade Apr 05 '15 at 11:45
0
  ImageIcon icon=new ImageIcon(getClass().getResource("path Name of image"));
  buttonobj.setIcon(icon);
Deepak Singh
  • 460
  • 2
  • 7
  • 19