0

I'm trying to create an application that requires user login. I've used SceneBuilder and FXML file for the interface. I now have to retrieve data from a SQLite database (I've named the table with the data as "Users"). When I run this program, it throws a NullPointerException (I already data stored on the table). How do I fix it?

//P.S. I use IntelliJ edit the database from the IDE itself.

enter image description here

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Controller {

    @FXML TextField username;
    @FXML TextField password;
    @FXML Label warning;
    Connection c;
    PreparedStatement pst;
    ResultSet rs;

    public void loginButtonClicked() throws IOException {
        try {
            String query = "select * from Users where Username=? and Password=?";
            pst = c.prepareStatement(query);
            pst.setString(1, username.getText());
            pst.setString(2, password.getText());
            rs = pst.executeQuery();

            if (rs.next()) {
                warning.setText("Successful");
            } else {
                warning.setText("Not Successful");
            }

        } catch (Exception e) {
            System.err.println(e);
        }
    }


    public void cancelButtonClicked(ActionEvent event) throws IOException {
        System.out.println("User has cancelled login...");

        ((Node)event.getSource()).getScene().getWindow().hide();
    }
}
yole
  • 92,896
  • 20
  • 260
  • 197
Karthik
  • 1
  • 2
  • You never [get a database connection](https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html) (`c` is null). Also see: [How does the SQL injection from the “Bobby Tables” XKCD comic work?](http://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work) and [How to avoid SQL injection and other security failure in JavaFX desktop application](http://stackoverflow.com/questions/28109969/how-to-avoid-sql-injection-and-other-security-failure-in-javafx-desktop-applicat) – jewelsea Dec 16 '16 at 23:50
  • Hey! Thanks a lot for the feedback. I have a method in the main class to checks for the connection. I tried the code without using FXML (using just javafx) and it worked perfectly. Could there be any other problem? I'd appreciate it a lot if you could run it in an IDE and fix the problem. I have a deadline to meet and am clueless as to what is wrong. – Karthik Dec 27 '16 at 19:58

1 Answers1

0

You should close your connection At the try statement add after else pst. close(); rs. close();