-2

I'm begginer at this that's probably why I'm having this error while I'm trying to do something very simple.

I just want to get the current user ID and use it in other classes. But I'm getting NullPointerException Error for the ExecuteQuery() line.

Let me share the code:

public class LoginPage extends javax.swing.JFrame {

private Connection conn=null;
private ResultSet rs=null;
private PreparedStatement pst=null;
private PreparedStatement sta=null;

ConnectionDB connect=new ConnectionDB();


public LoginPage() {
    initComponents();
}

public void getCurrentUser(){
    try{
            PreparedStatement c;
            conn=connect.getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users where Mail=?");
            stmt.setString(1, lMail.getText());
            ResultSet rss=sta.executeQuery();
            if(rss.next()){
                int CurrentUserID=rss.getInt("ID");
            }
        }
        catch(SQLException ex){
            System.out.println("SQL Exception Error!1");
        }
}

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            

    String sql="SELECT * from users where Mail=? and Password=?";
    try{
        conn=connect.getConnection();
        pst=conn.prepareStatement(sql);
        pst.setString(1,lMail.getText());
        pst.setString(2,lPass.getText());
        rs=pst.executeQuery();

    if(rs.next()){
        getCurrentUser();        
        JOptionPane.showMessageDialog(null, "Welcome!");
        new ListPage().setVisible(true);
        dispose();
    }
    else
    {
        JOptionPane.showMessageDialog(null, "Wrong mail-password combination!");
        lPass.setText("");
    }
    }
    catch(SQLException ex){
        System.out.println("SQL Exception Error!");
    }
}                             

"ResultSet rss=sta.executeQuery();" is the NullPointerException part.

I gave hours to solve this but I couldn't so I need your help.

Thank you

Lito
  • 17
  • 2

1 Answers1

0

You initialize

private PreparedStatement sta=null;

Hence, sta is null and giving you NullPointerException.

You may try something depending on your project,

sta = new PreparedStatement()

Or

ResultSet rss = stmt.executeQuery(); //stmt instead of sta
mazhar islam
  • 5,561
  • 3
  • 20
  • 41