Getting NullpointerException in JDBC code - java

The following code is throwing a NullPointerException - I don't know where the problem is. I am using an Excel spreadsheet as a backend.
//actionlistener for btnfetch
btnfetch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
String name="";
d1 = (java.util.Date)formatter.parse(textdate.getText());
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.sql.Date sqld=null;
ResultSet rs=st.executeQuery("select * from [ARNUM$]");
String getname=null;
while(rs.next())
{
getname=rs.getString(1);
sqld=rs.getDate(2);
System.out.println(getname+" "+sqld+" "+sqlDate);
if(sqlDate.compareTo(sqld)==0)
{
name=name+" "+getname;
name=name.toUpperCase();
}
System.out.println(name);
}
if(name.length()==0)
{
JOptionPane.showMessageDialog(
pnlp4,
"No Name having "+textdate.getText(),
"Warning",
JOptionPane.WARNING_MESSAGE
);
}
else
{
textname.setText(name);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}//end actionPerformed
}); //end addActionListener

The field value of sqld might be null. Now unfortunately sqlDate.compareTo(null) will throw a NullPointerException. (Other compareTo's behave better.)

Related

How to destroy a frame by clicking on a button?

I want to destroy the frame by clicking on a button. I searched everywhere and it seems that I'm doing this right. but it is not working.
public class LoginWindow {
public void CreateLoginWindow () {
/** Set Style to Main Frame **/
JFrame main_window = new JFrame();
main_window.setUndecorated(true);
main_window.setLocationRelativeTo(null);
main_window.setLayout(new BorderLayout());
main_window.setLayout(new FlowLayout());
main_window.setVisible(false);
main_window.setContentPane(new JLabel(new ImageIcon("images/MainWindow-bg.jpg")));
main_window.setExtendedState(JFrame.MAXIMIZED_BOTH);
main_window.setSize(1920,1080);
main_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/** Some Codes **/
JButton login_button = new JButton("Click to Exit");
login_button.setBounds(920,480,120,45);
/** Login Button Action **/
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
main_window.dispose();
}
});
main_window.add(login_button);
main_window.setVisible(true);
}
}
It seems ValidateLogin validateLogin = new ValidateLogin(); Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText()); make some problems.
And this is my ValidateLogin Class :
public class ValidateLogin {
public Boolean ValidateLoginAction (String username, String password){
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
if ( right_password.equals(password) ){
return true;
} else {
return false;
}
}
}
And this is my ConnectToDB Class :
public class ConnectToDB {
/** Connect to Database **/
private Connection connect() {
String url = "jdbc:sqlite:E://Resturant Project/db/Resturant.db";
Connection connection = null;
try {
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return connection;
}
/** Get Password of an Username **/
public String GetPassOfAnUsername(String username){
String password = "SELECT Password FROM Person WHERE UserName = '" + username +"'";
try (Connection connection = this.connect();
PreparedStatement statement= connection.prepareStatement(password);
ResultSet results = statement.executeQuery()) {
return results.getString("Password");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
}
And this is my MainWindow Class :
public class MainWindow {
public static void main(String[] args) {
LoginWindow loginWindow = new LoginWindow();
loginWindow.CreateLoginWindow();
}
}
I have tried and I am able to close the window and jvm exits also. I provide below the button action code snippet.
login_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ValidateLogin validateLogin = new ValidateLogin();
Boolean valid = validateLogin.ValidateLoginAction(username_field.getText(),password_field.getText());
}
catch(Exception ex) {
//handle exception
}
finally {
main_window.dispose();
}
}
});
Have the username_field and password_field variables been instantiated somewhere? Perhaps the line where you are accessing the getText() method is throwing a NullPointerException when the actionPerformed method is being called and so the program never reaches the main_window.dispose() line.
Try checking if both of those variables are null when the actionPerformed method is being executed before you try to access the getText() method from them.
On a further note, check if the connection the database is being established successfully.
ConnectToDB validate_login = new ConnectToDB();
String right_password = validate_login.GetPassOfAnUsername(username);
The second line might also throw a NullPointerException in case validate_login is null because your code will return null from your ConnectToDB() constructor in case the connection fails.

JTextfield - String split and intparse

I am working on a turtle graphics project and I'm attempting to retrieve a user input from a jtextfield (commField) which should be like: ' forward 100 ' I've attempted to do a string split and intparse however when the program is run, even when a correct command is entered it will go to the message error dialogue. After a few hours of turning the cogs in my brain I'm struggling to figure out why and so am asking for any help. If more of my code is needed for an answer that is fine, perhaps I'm focusing on the wrong thing.
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
}
});
Below is the full code block for those who want it:
commField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(commField.getText().contains("penup")) {
graphicsPanel.penUp();
}
else if(commField.getText().contains("pendown")) {
graphicsPanel.penDown();
}
else if(commField.getText().contains("turnright")) {
graphicsPanel.turnRight();
}
else if(commField.getText().contains("turnleft")) {
graphicsPanel.turnLeft();
}
else if(commField.getText().contains("forward")) {
String cForward = commField.toString();
String[] cForwardArray = cForward.split("\\s+");
try {
int distance = Integer.parseInt(cForwardArray[1]);
graphicsPanel.forward(distance);
System.out.println(commField);
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("backward")) {
String cBackward = commField.toString();
String[] cBackwardArray = cBackward.split("\\s+");
try {
int distance = Integer.parseInt(cBackwardArray[1]);
graphicsPanel.backward(distance);
graphicsPanel.repaint();
}
catch (Exception ev) {
JOptionPane.showMessageDialog(textArea,
"Invaild or missing parameter, check the help section\n"
+ "for more information on Commands");
}
}
else if(commField.getText().contains("black")) {
graphicsPanel.black(Color.black);
}
else if(commField.getText().contains("green")) {
graphicsPanel.green(Color.green);
}
else if(commField.getText().contains("red")) {
graphicsPanel.red(Color.red);
}
else if(commField.getText().contains("reset")) {
graphicsPanel.clear();
}
else {
JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
}
commField.setText("");
graphicsPanel.repaint();
}
});
Line of interest:
String cForward = commField.toString();
JTextField.toString() does not return the content of the JTextField.
I checked my java 8 sources and found the following:
public String toString() {
return getClass().getName() + '[' + paramString() + ']';
}
However, the toString() method is intended to be a debugging utility. Unless its behavior is explicitly documented it is not recommended to rely on it programmatically.
For retrieving its text content, JTextField provides a separate method: JTextComponent#getText(). The line should therefore be changed to:
String cForward = commField.getText();

Custom JtextField proprety [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've created a custom JtextField but any proprety defined method don't working like getText or SetText when I call it in the main JFrame.
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class JTextFieldDecimal extends JTextField {
private static final long serialVersionUID = 1L;
public JTextFieldDecimal()
{
super();
addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c =e.getKeyChar();
if(!((c>='0') && (c<='9') ||
(c==KeyEvent.VK_BACK_SPACE) ||
(c==KeyEvent.VK_DELETE)))
{
getToolkit().beep();
e.consume();
}
}
});
}
}
when I click in validation button in jframe Produit the compiler give me an error and point to line 98 wich content my statement parameter of Custom JtextField named txtPrixHT.
btnValider.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection cn=null;
PreparedStatement pst =null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost/gesticom", "root","");
//String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT,PrRemise,PrPrixAchat,PrStockAlerte,PrStockReel) values (?,?,?,?,?,?,?)";
String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT) values (?,?,?)";
pst=cn.prepareStatement(sqlAdd,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, txtCodebarre.getText());
pst.setString(2, txtDesignation.getText());
pst.setString(3,txtPrixHT.getText());
pst.execute();
rs=pst.getGeneratedKeys();
if(rs.next())
{
txtIdprod.setText(rs.getString(1));
JOptionPane.showMessageDialog(null, "Nouveau Produit créé", "Fournisseur",JOptionPane.INFORMATION_MESSAGE);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try
{
cn.close();
pst.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
});
For an alternative to your formatted text field, I would propose you don't try to validate the input yourself. You can use a JFormattedTextField that allow you to do it for you when the focus is lost. Here is a quick sample
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter()
);
This will use the Locale of the JVM to format the number like expected (simpler for Decimal values). If you want only to take integers, provide an integer format
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(
NumberFormat.getIntegerInstance()
)
);
You want to always have two decimal digit like 5.00, define it in the NumberFormat :
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(nf)
);
You can find more information about this on How to Use Formatted Text Fields

Error getting value from jdatechooser and adding it to database java

How can I show jcalender?
How to get the selected value from it and add it to database?
From google I found a file called jcalender-1.4. I've added it to the jframe but when I try to get selected value from it and add it to the database it shows error. Table is created but error shows while inserting values. The exception in insertion method is shown. I've tried to print the value the value of db9 by commenting the insertData method and it shows null. Below is the link of JCalender jar file that i've used.
https://www.dropbox.com/s/yxe86ylfm4u6be8/jcalendar-1.4.jar?dl=0
JButton btnNewButton = new JButton("New Reservation");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
db1=textField.getText();
db2=textField_1.getText();
db3=textField_2.getText();
db4=textField_3.getText();
db5=textField_4.getText();
db6=textField_5.getText();
db7=textField_6.getText();
db8=(String)comboBox.getSelectedItem();
db9=dateChooser.getDate();
db10=textField_7.getText();
db11=(String)comboBox_1.getSelectedItem();
db12=(String)comboBox_2.getSelectedItem();
db13=dateChooser_1.getDate();
db14=dateChooser_2.getDate();
try {
insertData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void createTable() throws Exception{
try{
Connection con=getConnection();
PreparedStatement create =con.prepareStatement("CREATE TABLE IF NOT EXISTS hotelDetails(_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(65),"
+ "surname varchar(65),address varchar(65),cnic varchar(65),mobileNo varchar(65),email varchar(65),city varchar(65),gender varchar(65),dob Date,country varchar(65),roomType varchar(65),"
+ "roomNo varchar(65),checkin Date,checkout Date)");
create.executeUpdate();
System.out.println("Table Created");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Table Not Created.Try Again","Error", JOptionPane.ERROR_MESSAGE);
}
} public static void insertData() throws Exception{
try{
Connection con=getConnection();
PreparedStatement posted=con.prepareStatement("INSERT INTO hotelDetails(name,surname,address,cnic,mobileNo,email,city,gender,dob,country,roomType,roomNo,checkin,checkout)VALUES('"+db1+"','"+db2+"','"+db3+"','"+db4+"','"+db5+"','"+db6+"','"+db7+"','"+db8+"','"+db9+"','"+db10+"','"+db11+"','"+db12+"','"+db13+"','"+db14+"')");
posted.executeUpdate();
System.out.println("Values Inserted");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't Insert Data","Error", JOptionPane.ERROR_MESSAGE);
}
}

My program's Action Listener won't work

It's me again and I just can't seem to get this code to work. I'm basically asking for any advice on why the button does nothing when clicked. Would you like me to attach the source code?
The method I'm trying to implement:
public static void UserInput() {
try {
stmt = connect.createStatement();
ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
while (res.next()) {
if (res.getString("Username").equals(usernameField.getText())) {
if (res.getString("Password").equals(passwordField.getPassword())) {
JOptionPane.showMessageDialog(null, "Correct", "Correct",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Error. Incorrect "
+ "username or password.", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
res.close();
stmt.close();
connect.close();
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
And here's how I'm calling it:
if(firstTime == false) {
JavaDB jdb = new JavaDB();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
And here's the actionListner:
submit = new JButton("Submit");
c.add(submit);
submit.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
if(e.getSource().equals(submit)) {
UserInput();
}
}
}); ;
If you need anymore let me know. I've been teaching myself Java and I don't really know what to learn so any tips will be welcomed. I'm also new to stack overflow and posting code so any thing you can give me will be more than appreciated. Thanks in advance.
Edit: I now added a class for event handling with the Thread inside of it like this;
public class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(submit)){
Thread th = new Thread(new JavaDB());
th.start();
th.run();
try {
th.wait();
} catch (InterruptedException e1) {
}
}
else{
System.exit(0);
}
}
And I changed UserInput to run(). However,now when I click the submit button,The GUI disappears. Just for a reference you might need, here's my main method:
public static void main(String args[]) throws SQLException,
InterruptedException {
createConnection();
boolean firstTime = firstTime();
if (firstTime) {
JavaDB db = new JavaDB("");
db.createAccount();
try {
connect = DriverManager
.getConnection("jdbc:derby:\\KeithDB;shutdown=true");
} catch (SQLException XJ015) {
}
}
if (firstTime == false) {
JavaDB jdb = new JavaDB();
Thread th = new Thread();
}
JavaDB window = new JavaDB("");
window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
Anything else you need,let me know
PasswordDemo, as shown in How to Use Password Fields, would be a good starting point for your study, and it would make an effective sscce.
Addendum: Absent a complete example or knowledge of what database you are using, I got the following result,
Version: H2 1.3.157 (2011-06-25) 1.3
by running the following modification to PasswordDemo against H2 Database:
if (isPasswordCorrect(input)) {
try {
Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
Addendum: I got the following result,
Version: Apache Derby 10.6.2.1 - (999685) 10.6
by running the following modification to PasswordDemo against Apache Derby:
if (isPasswordCorrect(input)) {
try {
EmbeddedDataSource ds = new EmbeddedDataSource();
ds.setDatabaseName("/home/trashgod/.netbeans-derby/dbtest");
Connection conn = ds.getConnection("sa", "secret");
DatabaseMetaData metaData = conn.getMetaData();
System.out.println("Version:"
+ " " + metaData.getDatabaseProductName()
+ " " + metaData.getDatabaseProductVersion()
+ " " + metaData.getDatabaseMajorVersion()
+ "." + metaData.getDatabaseMinorVersion());
} catch (SQLException ex) {
ex.printStackTrace(System.err);
}
} ...
I finally got it to work! I had another constructor with the same variable names and my call to the JTextFields were mistaken to be the call to the other constructor. The foo statements really helped!!! Thank you everyone!

Categories