0

I'm having a problem with my code in java. It is supposed to insert data into a database but it's returning a nullpointerexception. Here is my code.

package client;
import java.sql.*;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class AddCon {


    private Connection conn;
private JFrame frmAddContract;
private JTextField ContractNo;
private JTextField EngagerName;
private JTextField contNo;
    private JTextField month;
    private JTextField day;
private JTextField year;
private JTextField tme;
private JTextField cladd;
private JTextField eventadd;
private JTextField textField_fp;
    private JTextField refer;


/**
 * Launch the application.
 */
public static void main(String[] args) {



        EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                AddCon window = new AddCon();
                window.frmAddContract.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public AddCon() {

        try{
           //Load database driver and connect
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/KusinaNiKambal","root","1234");
                Statement stmt = null;
                stmt = conn.createStatement();}

        catch (Exception e){
                JOptionPane.showMessageDialog(null, e);}

/**
 * Initialize the contents of the frame.
 */
    initialize();
}
private void initialize() {
    frmAddContract = new JFrame();
    frmAddContract.setResizable(false);
    frmAddContract.setTitle("Add Contract");
    frmAddContract.setBounds(100, 100, 450, 640);
    frmAddContract.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmAddContract.getContentPane().setLayout(null);

    ContractNo = new JTextField();
    ContractNo.setBounds(38, 32, 152, 20);
    frmAddContract.getContentPane().add(ContractNo);
    ContractNo.setColumns(10);

    JLabel lblContract = new JLabel("Contract #");
    lblContract.setBounds(38, 18, 76, 14);
    frmAddContract.getContentPane().add(lblContract);

    JLabel lblEngager = new JLabel("Engager");
    lblEngager.setBounds(38, 63, 48, 14);
    frmAddContract.getContentPane().add(lblEngager);

    EngagerName = new JTextField();
    EngagerName.setBounds(38, 78, 152, 20);
    frmAddContract.getContentPane().add(EngagerName);
    EngagerName.setColumns(10);

    contNo = new JTextField();
    contNo.setBounds(38, 128, 152, 20);
    frmAddContract.getContentPane().add(contNo);
    contNo.setColumns(10);

    JLabel lblNewLabel = new JLabel("Contact #");
    lblNewLabel.setBounds(38, 109, 86, 14);
    frmAddContract.getContentPane().add(lblNewLabel);

    month = new JTextField();
    month.setBounds(38, 255, 116, 20);
    frmAddContract.getContentPane().add(month);

    day = new JTextField();
    day.setBounds(181, 255, 81, 20);
    frmAddContract.getContentPane().add(day);

    year = new JTextField();
    year.setBounds(294, 255, 86, 20);
    frmAddContract.getContentPane().add(year);
    year.setColumns(10);

    JLabel lblMonth = new JLabel("Month in number format");
    lblMonth.setBounds(38, 236, 100, 14);
    frmAddContract.getContentPane().add(lblMonth);

    JLabel lblDay = new JLabel("Day");
    lblDay.setBounds(181, 236, 48, 14);
    frmAddContract.getContentPane().add(lblDay);

    JLabel lblYear = new JLabel("Year");
    lblYear.setBounds(294, 236, 48, 14);
    frmAddContract.getContentPane().add(lblYear);

    JLabel lblEventDate = new JLabel("Event Date");
    lblEventDate.setBounds(38, 222, 76, 14);
    frmAddContract.getContentPane().add(lblEventDate);

    tme = new JTextField();
    tme.setBounds(38, 307, 59, 20);
    frmAddContract.getContentPane().add(tme);
    tme.setColumns(10);

    cladd = new JTextField();
    cladd.setBounds(38, 180, 363, 31);
    frmAddContract.getContentPane().add(cladd);
    cladd.setColumns(10);

    JLabel lblAddress = new JLabel("Client Address");
    lblAddress.setBounds(38, 159, 98, 14);
    frmAddContract.getContentPane().add(lblAddress);

    JLabel lblTime = new JLabel("Time");
    lblTime.setBounds(38, 286, 60, 14);
    frmAddContract.getContentPane().add(lblTime);



    eventadd = new JTextField();
    eventadd.setBounds(38, 358, 373, 50);
    frmAddContract.getContentPane().add(eventadd);
    eventadd.setColumns(10);

    JLabel lblEventAddress = new JLabel("Event Address");
    lblEventAddress.setBounds(38, 338, 116, 14);
    frmAddContract.getContentPane().add(lblEventAddress);

    textField_fp = new JTextField();
    textField_fp.setBounds(38, 454, 276, 20);
    frmAddContract.getContentPane().add(textField_fp);
    textField_fp.setColumns(10);

    JLabel lblFilepathOfContract = new JLabel("Filepath of  Contract - the PDF file");
    lblFilepathOfContract.setBounds(38, 431, 116, 14);
    frmAddContract.getContentPane().add(lblFilepathOfContract);

    JButton btnBrowse = new JButton("Browse...");
    btnBrowse.setBounds(324, 453, 89, 23);
    frmAddContract.getContentPane().add(btnBrowse);
            btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
                        final JFileChooser fc = new JFileChooser();
                        int returnVal = fc.showOpenDialog(null);
                        String filepath = fc.getSelectedFile().getAbsolutePath();
                        textField_fp.setText(filepath);
                    }
    });

    refer = new JTextField();
    refer.setBounds(38, 510, 276, 20);
    frmAddContract.getContentPane().add(refer);
    refer.setColumns(10);

    JLabel lblEncodedBy = new JLabel("Referred By");
    lblEncodedBy.setBounds(38, 485, 116, 14);
    frmAddContract.getContentPane().add(lblEncodedBy);




    JButton btnAdd = new JButton("Add");
    btnAdd.setBounds(101, 560, 89, 23);
    frmAddContract.getContentPane().add(btnAdd);
            btnAdd.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {

            try{

                String cntr = ContractNo.getText();
                String en = EngagerName.getText();
                String cont = contNo.getText();
                String mo = month.getText();
                String d = day.getText();
                String yr = year.getText();
                String dte = yr + "-" + mo + "-" + d;
                String cla = cladd.getText();
                String tm = tme.getText() + ":00";
                String evadd = eventadd.getText();
                String filepath = textField_fp.getText();
                String ref = refer.getText();


                String SQL = "insert into cis "+
                    "values ('"+cntr+"','"+en+"','"+
                    cont+"','"+cla+"' '"+dte+"','"+tm+"','"+
                    evadd+"','"+filepath+"','"+ref+")";
                PreparedStatement stmt = conn.prepareStatement(SQL);
                ResultSet rs = stmt.executeQuery();

            }
            catch(Exception e){
                JOptionPane.showMessageDialog(null, e);
            }
                }


            });

    JButton btnCancel = new JButton("Cancel");
    btnCancel.setBounds(225, 560, 89, 23);
    frmAddContract.getContentPane().add(btnCancel);
             btnCancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                     frmAddContract.setVisible(false);
                }



    });
}
}

Sorry, i'm not really that experienced in java programming and this is my first time making a code for querying databases.

1
  • which line did u got the exception? Commented Jan 18, 2014 at 14:17

1 Answer 1

1

You do never initialize your conn instance variable. This will lead to a NullPointerException (at least) in this line:

PreparedStatement stmt = conn.prepareStatement(SQL);
                         ^------------ NEVER INITIALIZED

public class AddCon {
    private Connection conn;

...

// constructor
public AddCon() {
    try{
        //Load database driver and connect
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(<your parameters>);
        ^----------- MISTAKE
...

In the above code you create a connection, but instead of assigning it to the instance variable you just use a local variable. Replace that line with:

this.conn = DriverManager.getConnection(<your parameters>);

Edit: Please always post the stacktrace in case of exceptions!

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

3 Comments

@user3209957: you're welcome. In case this is the answer to your question, please mark it as such (there's a button on top of the answer).
anyway, how can i add a warning message (yes, no option) confirming the action on the btnAdd button(if yes, the app will update the database, if no, the action would not take place)?
@user3209957: I must admit that I'm not a swing expert, but there's a Q&A regarding modal dialogs in Swing: stackoverflow.com/questions/1481405/…

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.