Hi everyone please help on this:
I am developping a program in java, but I need the user to enter his/her details if they are compatible with the values in a database table he/she get access to the main interface.
here is what I've done so far

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

public class loginForm implements ActionListener{
   private String userid="";
   private String pass="";
   private String url="JDBC:ODBC:Student";
   private Connection cn=null;
   String username="";
   String password="";


   JLabel jlbUserName, jlbPass;
   JTextField jtfUserName;
   JPasswordField jpfPass;
   JButton jbnOK, jbnCancel, jbnRegister, jbnExit;
   JFrame loginFrame;
   JPanel txt1panel = new JPanel();
   JPanel txt2panel = new JPanel();
   JPanel cmdpanel = new JPanel();

      public static void main(String args[]){
      new loginForm();
   }

    private Statement stat;
    private ResultSet rs;
    private String query = new String("SELECT* FROM LoginTable");
        // constructor
	public  loginForm(){
            // initialize all GUI components
            loginFrame= new JFrame("Login Form");
            loginFrame.getContentPane();

            txt1panel.setLayout(new FlowLayout());
            txt2panel.setLayout(new FlowLayout());
            cmdpanel.setLayout(new FlowLayout());
            //setting the Frame's properties
            loginFrame.setSize(250,400);
            loginFrame.setVisible(true);
            loginFrame.setResizable(false);


            jlbUserName = new JLabel("Username");
            jlbPass = new JLabel("Password");
            jtfUserName = new JTextField(20);
            jpfPass = new JPasswordField(20);
            jbnOK = new JButton("OK");
            jbnCancel = new JButton("Clear");
            jbnRegister = new JButton("Register");
            jbnExit = new JButton("Exit");

            // add GUI components to the JFrame
            txt1panel.add(jlbUserName,BorderLayout.LINE_START);
            txt1panel.add(jtfUserName,BorderLayout.LINE_END);
            loginFrame.add(txt1panel, BorderLayout.NORTH);
            txt2panel.add(jlbPass,BorderLayout.LINE_START);
            txt2panel.add(jpfPass,BorderLayout.LINE_END);
            loginFrame.add(txt2panel, BorderLayout.CENTER);
            cmdpanel.add(jbnOK);
            cmdpanel.add(jbnCancel);
            cmdpanel.add(jbnRegister);
            cmdpanel.add(jbnExit);
            loginFrame.add(cmdpanel, BorderLayout.PAGE_END);
            loginFrame.pack();
            jbnOK.addActionListener(this);
            jbnCancel.addActionListener(this);
            jbnRegister.addActionListener(this);
            jbnExit.addActionListener(this);
		getConnection();		//Create Connection to the Database
	}

	public Connection getConnection(){

		try {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

		}
		catch(java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}

		try {
			cn = DriverManager.getConnection(url, userid, pass);
		}
		catch(SQLException ex) {
			System.err.println("SQLException: " + ex.getMessage());
		}

		return cn;
	}

      public void actionPerformed(ActionEvent evt){
          if (evt.getSource()==jbnOK){
                OkButton();
          }
          else if (evt.getSource()==jbnCancel){
              ClearButton();
          }
          else if (evt.getSource()==jbnRegister){
              RegButton();
          }
          else if(evt.getSource()==jbnExit){
              	        int selection = JOptionPane.showConfirmDialog(null,
	                    "Want to leave the Program", "ExitBox",
	                    JOptionPane.YES_NO_OPTION,
	                    JOptionPane.QUESTION_MESSAGE);
	        if( selection == JOptionPane.YES_OPTION ) {
	            System.exit(0);
	        }
                else{
                }
          }
      }

    private void ClearButton() {
        jtfUserName.setText("");
        jpfPass.setText("");
    }

    private void OkButton() {
        try{
            rs =stat.executeQuery(query);
            while(rs.next()){
                if(rs.getString("username").equals(jtfUserName.getText())&& rs.getString("password").equals(jpfPass.getText())){
                    JOptionPane.showMessageDialog(null, "Login Successful");                 
                    PatientReg patient = new PatientReg();
                    patient.init();
                    patient.buildGUI();
                                    loginFrame.hide();
                    
                }
                else{
                    JOptionPane.showMessageDialog(null, "Attempt failed");
                }
            }
        }catch(Exception e){
            System.err.println(e.getMessage());
        }
    }

 
   private void RegButton() {
      	   	username    = jtfUserName.getText();
                password = jpfPass.getText();

	   	if(username.equals("")){
	   		JOptionPane.showMessageDialog(null, "Please enter Username.");
	   	}
         else{

	 //create a UserInfo object and pass it to loginForm to save it
         UserInfo user = new UserInfo(username,password);
         loginForm log = new loginForm();
	 log.saveDetails(user);
         JOptionPane.showMessageDialog(null, "User Info Saved");
         loginFrame.hide();
         }
    }
   public void saveDetails (UserInfo user){
		try
		{
	String sql = "INSERT INTO LoginTable VALUES (?,?) ";

			// Create a Preparedstatement
 			PreparedStatement ps = cn.prepareStatement(sql);

			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPass());
			ps.executeUpdate();
		}
		catch(Exception e){
			System.err.println(e);
		}

     }


}

everything works fine except the ok button which when clicked gives the exception

null

I don't get it please assist:)
Thanks in advance!

Recommended Answers

All 11 Replies

First of all you need to close the connection, statement and resultSet every time after you have used them.
Second try to print the stack trace of the exception. (e.printStacktrace()). And try to find at which line of the class you get that exception. If it is a NullPointerException, which probably is, it means that you are using something which is null, that you haven't initialized.

And have a seperate class that does the database handling. Have a seperate method that does this:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
open connection
create statement
run query that returns ResultSet
get the data from ResultSet
return;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}

First of all you need to close the connection, statement and resultSet every time after you have used them.
Second try to print the stack trace of the exception. (e.printStacktrace()). And try to find at which line of the class you get that exception. If it is a NullPointerException, which probably is, it means that you are using something which is null, that you haven't initialized.

And have a seperate class that does the database handling. Have a seperate method that does this:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
open connection
create statement
run query that returns ResultSet
get the data from ResultSet
return;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}

I don't get it, may I remind you I am a beginer in java so If you please be kind an materialize those explanations by concrete code lines. Thanks for the support

I don't get it, may I remind you I am a beginer in java so If you please be kind an materialize those explanations by concrete code lines. Thanks for the support

I did what you instructed now it's comparing values with the database values but the problem is it doesn't give me direct access it says first attempt failed as specified in the pop up box then when I press ok multiple times it shows the main interface although the values entered are compatible with the values in the database.
here the code I have now:

private void OkButton() {
        try{
            stat =cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            rs =stat.executeQuery(query);
            rs.first();
            while(rs.next()){
                if(rs.getString("username").equals(jtfUserName.getText())&& rs.getString("password").equals(jpfPass.getText())){
                    JOptionPane.showMessageDialog(null, "Login Successful");                 
                    PatientReg patient = new PatientReg();
                    patient.init();
                    patient.buildGUI();
                                    loginFrame.hide();
                    cn.close();
                    rs.close();
                    stat.close();
                }
                else{
                    JOptionPane.showMessageDialog(null, "Attempt failed");
                }
            }
        }catch(SQLException e){
            System.err.println(e.getMessage());
        }
    }

Help again! Please...

Becuase you do this:

while(rs.next()) {
  if (success) {
     show page
  } else {
     error
  }
}

If you give wrong credentials the error message will be printed many times since it is inside a loop. Assuming that you have many entries in the database and only one matches the values you entered. When you reach the row that has the same "username", "password" entered the patient gui will be displayed but the while will continuing looping.

I already told you the right way to do things and you didn't follow them. If you are such a beginer that you can't even create a single method that returns true or false:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//open connection
//create statement
//run query that returns ResultSet

//get the data from ResultSet
while(rs.next()) {
  if ( rs.getString("username").equals(username)  &&    rs.getString("password").equals(password) ) {
     return true;
  }
}
return false;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}

Or can't even write a query such as this:

public boolean validate(String user, String pass) {
  String query = "select username, password from LoginTable where  username = '" + user + "' and password = '" + pass + "'";
}

Or follow this simple structure:

// declare Connection, Statement, ResultSet
try {
// Initialize Connection, Statement, ResultSet
} catch (Exception e) {
    throw e;
} finally {
   // close Connection, Statement, ResultSet if they are not null
}

Then you shouldn't be doing something like that.
Don't have Connection, Statement, ResultSet be global. Have locally at the method that will get you the results

Becuase you do this:

while(rs.next()) {
  if (success) {
     show page
  } else {
     error
  }
}

If you give wrong credentials the error message will be printed many times since it is inside a loop. Assuming that you have many entries in the database and only one matches the values you
entered. When you reach the row that has the same "username", "password" entered the patient gui will be displayed but the while will continuing looping.

I already told you the right way to do things and you didn't follow them. If you are such a beginer that you can't even create a single method that returns true or false:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//open connection
//create statement
//run query that returns ResultSet

//get the data from ResultSet
while(rs.next()) {
  if ( rs.getString("username").equals(username)  &&    rs.getString("password").equals(password) ) {
     return true;
  }
}
return false;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}

Or can't even write a query such as this:

public boolean validate(String user, String pass) {
  String query = "select username, password from LoginTable where  username = '" + user + "' and password = '" + pass + "'";
}

Or follow this simple structure:

// declare Connection, Statement, ResultSet
try {
// Initialize Connection, Statement, ResultSet
} catch (Exception e) {
    throw e;
} finally {
   // close Connection, Statement, ResultSet if they are not null
}

Then you shouldn't be doing something like that.
Don't have Connection, Statement, ResultSet be global. Have locally at the method that will get you the results

Hey thanks man you've been of great help! the values are now checked and all verify! but the problem now is if I enter wrong values it just gives nothing and the pop up doesn't show. Help me how could we tackle that? And I want it to stop when the user attempt to log in three times successively
here is the code I have: Thanks for your instructions

private void OkButton() throws SQLException {
       Connection conn = null;
       Statement stat = null;
       ResultSet rs = null;
       String user = jtfUserName.getText();
       String Pass = jpfPass.getText();
       String query = null;
       try{
           //opening the connection
           conn = DriverManager.getConnection(url, userid, pass);
           // create the statement
            stat =conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
            //the query that returns the Resultset
            query = "select username, password from LoginTable where  username = '"
            + user + "' and password = '" + Pass + "'";
            //get the data from the Resultset
            rs =stat.executeQuery(query);
            while(rs.next()){
                if(rs.getString("username").equals(user)&& rs.getString("password").equals(Pass)){
                    JOptionPane.showMessageDialog(null, "Login Successful");                 
                    PatientReg patient = new PatientReg();
                    patient.init();
                    patient.buildGUI();
                                    loginFrame.hide();
                }
                else{
                        int selection = JOptionPane.showConfirmDialog(null,
	                "Attempt failed! Do you want to leave", "Exit",
	                JOptionPane.YES_NO_OPTION,
	                JOptionPane.QUESTION_MESSAGE);
	                if( selection == JOptionPane.YES_OPTION ) {
	                System.exit(1);
                           }
                }
            }
        }catch(SQLException e){
            throw e;
        }
       finally{
         if (rs!=null) rs.close();
         if(conn!=null) conn.close();
         if(stat!=null) stat.close();
       }
             
    }

Thank you very much!!!

Since you put the username, password at the query, it means that if the query returns then the username, password given were in the database. You don't need to get the username, password from the database and compare them again. This will do:

if (rs.next()) {
 // success
} else {
 numberOfAttempts++;
 if (numberOfAttempts>3) {
   // exit   
 }
}

You'd better try to understand the code I give you and not just copy paste it

You'd better try to understand the code I give you and not just copy paste it

Maybe if you please could be more specific
Do I use the while loop or what for this

if (rs.next()) {
 // success
} else {
 numberOfAttempts++;
 if (numberOfAttempts>3) {
   // exit   
 }
}

Please explain a bit further. I did this

if(rs.next()){
                    JOptionPane.showMessageDialog(null, "Login Successful");                 
                    PatientReg patient = new PatientReg();
                    patient.init();
                    patient.buildGUI();
                                    loginFrame.hide();
                }
                else{
                    int numberOfAttempts=0;
                    while(numberOfAttempts<=3) {
                    JOptionPane.showMessageDialog(null, "Login failed, try Again");
                    }numberOfAttempts++ ;
                     if (numberOfAttempts>3) {
                     System.exit(1);
                     }               
              }

but it keeps on giving the pop up then I click ok it doesn't go away and allow me to enter again.

I cannot help if you don't follow my suggestions. This is what I wrote:

if (rs.next()) {
} else {
 [B]numberOfAttempts++;
 if (numberOfAttempts>3) {
   // Attempted to log unsuccessfully for 3 times
 }[/B]
}

And you wrote:

if(rs.next()){
                }
                else{
                    [B]int numberOfAttempts=0;
                    while(numberOfAttempts<=3) {
                    JOptionPane.showMessageDialog(null, "Login failed, try Again");[/B]
                    }
                    [B]numberOfAttempts++ ;
                     if (numberOfAttempts>3) {
                     System.exit(1);
                     }  [/B]             
              }

The while loop will always be true:

int numberOfAttempts=0;
while(numberOfAttempts<=3)

So it will never end. The idea is whenever you don't enter correct username, password to increase a counter. If the counter becomes greater than 3, (3 unsuccessful attempts) exit the application.
And you went and declared it in the else { .. }. Meaning that it will always be 0 and will never reach 3.
Can't you imagine where it should have been declared or you didn't think that upon successful log in to initialize it back to 0?

I cannot help if you don't follow my suggestions. This is what I wrote:

if (rs.next()) {
} else {
 [B]numberOfAttempts++;
 if (numberOfAttempts>3) {
   // Attempted to log unsuccessfully for 3 times
 }[/B]
}

And you wrote:

if(rs.next()){
                }
                else{
                    [B]int numberOfAttempts=0;
                    while(numberOfAttempts<=3) {
                    JOptionPane.showMessageDialog(null, "Login failed, try Again");[/B]
                    }
                    [B]numberOfAttempts++ ;
                     if (numberOfAttempts>3) {
                     System.exit(1);
                     }  [/B]             
              }

The while loop will always be true:

int numberOfAttempts=0;
while(numberOfAttempts<=3)

So it will never end. The idea is whenever you don't enter correct username, password to increase a counter. If the counter becomes greater than 3, (3 unsuccessful attempts) exit the application.
And you went and declared it in the else { .. }. Meaning that it will always be 0 and will never reach 3.
Can't you imagine where it should have been declared or you didn't think that upon successful log in to initialize it back to 0?

According to what you instructed this is what I came up with

int numberOfAttempts=0;
            if(rs.next()){
                    JOptionPane.showMessageDialog(null, "Login Successful");                 
                    PatientReg patient = new PatientReg();
                    patient.init();
                    patient.buildGUI();
                                    loginFrame.hide();
                  }else {
                    numberOfAttempts++;                 
                    if (numberOfAttempts>3) {
                    JOptionPane.showMessageDialog(null, "You Attempted to log unsuccessfully for 3 times");
                    System.exit(1);
                 }
                }

But still it is not giving anything when the details are wrong! Please I hope you understand, I just have very very little basic in java, and for my internship they gave me this to develop. Please be patient, I'm sorry for not being a quick learner. Thank you

Of course it doesn't print anything because you have things inside the if. And the if statement return false.
Every time you run that code the numberOfAttempts is initialized to zero. So it will never reach 3. This is not where you need to declare it.
You should add a "System.out.println" before the if to see what is the variable's value. Try to do that every time you are stuck.
Its value shouldn't be initialized to zero every time you run the code, that is why I didn't declare anywhere near that code.
It should be declared somewhere where its value isn't set to zero every time you try to log in. Perhaps as a global variable.


If you can't understand that, then you need to study more and don't do so complex things. There is nothing more I can explain on this matter. Everything you need so you can fix it, have been told.

You asked me why you don't see the message, when the if statement is right there in front of you, you wrote it. Don't you know what if statement do? Did I have to tell you that the code inside the if doesn't execute because the if is false?

If you have any more questions on something else then I will answer them. But these things are not for beginners as you mentioned.

Of course it doesn't print anything because you have things inside the if. And the if statement return false.
Every time you run that code the numberOfAttempts is initialized to zero. So it will never reach 3. This is not where you need to declare it.
You should add a "System.out.println" before the if to see what is the variable's value. Try to do that every time you are stuck.
Its value shouldn't be initialized to zero every time you run the code, that is why I didn't declare anywhere near that code.
It should be declared somewhere where its value isn't set to zero every time you try to log in. Perhaps as a global variable.


If you can't understand that, then you need to study more and don't do so complex things. There is nothing more I can explain on this matter. Everything you need so you can fix it, have been told.

You asked me why you don't see the message, when the if statement is right there in front of you, you wrote it. Don't you know what if statement do? Did I have to tell you that the code inside the if doesn't execute because the if is false?

If you have any more questions on something else then I will answer them. But these things are not for beginners as you mentioned.

Ok, I really can't thank you enough! I'm cool now with the Log In part, and my main interface is showing. All the button on the main interface are working, except the Get Info button which is supposed to give the rest of the patient Info given that the user select patient No from a Jlist . The problem here is that it gives for certain patientno but not for all. And one more thing could you help me on how to display those records in the JTable instead of the textfields? Thanks and here is the code snippet for the Get Info button

//Do Get Patient Info Button
    getBtn = new JButton("Get PatientInfo");
    getBtn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          rs.first();
          while ((rs.next())) {
            if (rs.getString("patientNo").equals(
                PatientNumberList.getSelectedValue()))
              break;
          }
          if (!rs.isAfterLast()) {
            jtfPnum.setText(rs.getString("patientNo"));
            jtfFname.setText(rs.getString("fname"));
	    jtfSname.setText(rs.getString("sname"));
	    jtfLocation.setText(rs.getString("location"));
	    jtfDOB.setText(""+ rs.getDate("dob"));
	    jtfDOR.setText(""+ rs.getDate("dor"));
	    jtfRace.setText(rs.getString("race"));
	    jtfGender.setText(rs.getString("gender"));
	    jtfStat.setText(rs.getString("status"));
	    jtfInit.setText(rs.getString("initials"));
	    jtfID.setText("" + rs.getLong("idnum"));

          }
        } catch (SQLException selectException) {
          displaySQLErrors(selectException);
        }
      }
    });

Thanks:icon_smile:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.