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");
            }
    }   
}
7
  • Can you post the stack trace? Commented Apr 4, 2015 at 12:46
  • @user7 The only error appearing on console is java.lang.NullPointerException Commented Apr 4, 2015 at 12:48
  • and nothing is being added to the database :( Commented Apr 4, 2015 at 12:48
  • In which line did your NullPointerException occur? Commented Apr 4, 2015 at 12:51
  • Please provide more details about the exact line where you get the NullPointerException since a human will ideally take longer to deduce this in comparison to the Jave runtime environment. Commented Apr 4, 2015 at 12:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

11 Comments

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 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..
But it says database connection succesful ! This line System.out.println("Database connection succesful to: " + url); executes.
@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??
@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..
|
0
  ImageIcon icon=new ImageIcon(getClass().getResource("path Name of image"));
  buttonobj.setIcon(icon);

1 Comment

You should add an explanation to your answer.

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.