0

I've experienced the problem that I can't find solution for it anywhere. I've been writing a simple application in JavaFx and somehow any of my variables that I'd like to store simply can't be possible. I mean...yes it is possible but only as long as I stay in any method, after I leave method it simply lose any data that should be stored in global variables ;/ So here is how my code look like: First is my main Class where I start program. I open here first JavaFx window and create object to run DataBase Connection

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
private static DBconnection connection;

@Override
public void start(Stage primaryStage) throws Exception{
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
    primaryStage.setTitle("Main Menu");
    primaryStage.setScene(new Scene(root, 300, 275));
    primaryStage.show();
}

public static DBconnection getinstance(){
    if(connection==null){
        connection = new DBconnection();
    }

    return connection;
}

public static void main(String[] args) {
    launch(args);

}
}

Next is my DBconnection Class (with some methods that are working quite ok...the only annoying thing is that I can't create connection once , but I must each time connect to database which is also a problem why I'm writing here:

import java.sql.*;

public class DBconnection {
public Statement stmt;
public Connection conn;
public ResultSet rs;
public String user,pass,dbURL;
public String userloginonline;

public DBconnection() {

    conn = null;
    stmt = null;
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        dbURL = "jdbc:sqlserver://localhost\\sqlexpress:1433;databaseName=projektDB;";
        user = "przemek";
        pass = "przemek";
        conn = DriverManager.getConnection(dbURL, user, pass);
    } catch (SQLException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}


public boolean createuser(String stringtosend) throws SQLException {
    try {
        conn = DriverManager.getConnection(dbURL, user, pass);
        rs = conn.createStatement().executeQuery(stringtosend);
    }catch (Exception e){
        if(e.getMessage().equals("ERROR!") )
            return false;
        e.printStackTrace();
    }
    return true;

}
public boolean getlogpw(String login,String password) throws SQLException {
    try {
        conn = DriverManager.getConnection(dbURL, user, pass);
        System.out.println("Login:"+userloginonline+" password:"+password);
        userloginonline=login;
        rs = conn.createStatement().executeQuery("Select * from Users where Username like \'"+login+"\'");
    }catch (Exception e){
        e.printStackTrace();
    }
    String LoginSql=" ",passwordsql=" ";
    while(rs.next()){
        LoginSql = rs.getString("Username");
        passwordsql = rs.getString("Upassword");
    }
    if(LoginSql.equals(login)&&password.equals(passwordsql))
        return true;
    else
        return false;
}

}

And the last important class is controller:

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;


import java.io.IOException;
import java.sql.SQLException;

public class Controller {
public String userloginonline;
Stageerr errorwindow;
DBconnection connection;
@FXML
private TextField login;
@FXML
private PasswordField pw1,pw2;
private String Slogin,Spw1,Spw2;
public void pressNewUser(ActionEvent event) throws IOException {
    windowopener windowopener = new windowopener(event,"mainwindow.fxml","Create new user");

}
@FXML
public void newUserAccept(ActionEvent event) throws IOException, SQLException {
    connection = Main.getinstance();
    Slogin=login.getText();
    Spw1=pw1.getText();
    Spw2=pw2.getText();


    if(Spw2.equals(Spw1) && !(Spw1.isEmpty()) &&!(Slogin.isEmpty())){
        if(connection.createuser("INSERT INTO Users (Username,Upassword) values (\'"+Slogin+"\',\'"+Spw1+"\')")){
        windowopener windowopener = new windowopener(event,"sample.fxml","Main Menu");
        }
        else errorwindow=new Stageerr(event,"ErrorWindow2.fxml");
    }
    else{
        errorwindow=new Stageerr(event);
    }


}
@FXML
public void authorizate(ActionEvent event) throws IOException, SQLException {
    Slogin=login.getText();
    Spw2=pw2.getText();
    System.out.println(Slogin+"  "+Spw2);
    connection=Main.getinstance();
    if(connection.getlogpw(Slogin,Spw2)){
        Slogin=login.getText();
        userloginonline=Slogin;
        windowopener windowopener = new windowopener(event,"Corewindow.fxml","Log In");}
    else{
        errorwindow=new Stageerr(event);
    }

}
public void About(ActionEvent event) throws IOException{
    Withouthide withouthide = new Withouthide(event,"Help.fxml","About");
}

public void pressLogin(ActionEvent event) throws IOException {
            windowopener windowopener = new windowopener(event,"Loginwindow.fxml","Log In");
}
public void presshide(ActionEvent event){   ((Node)(event.getSource())).getScene().getWindow().hide();   }
public void pressexit(ActionEvent event){
    System.exit(0);
}
@FXML
public void pressremoveacc(ActionEvent event) throws IOException, SQLException {
    Spw1=pw1.getText();
    Spw2=pw2.getText();
    System.out.println(userloginonline);
    connection=Main.getinstance();
    if(!(connection.getlogpw(userloginonline,Spw1))&&Spw1==Spw2){
        windowopener windowopener = new windowopener(event,"mainwindow.fxml","Log In");}
    else {
        errorwindow = new Stageerr(event);
    }
}
public void removeuserprocedure(ActionEvent event){
    Withouthide withouthide = new Withouthide(event,"Removeacc.fxml","Remove User");
}

}

In controller class, generally I've put all the methods that all the fxml files reference to it. So whenever I press button in any window , it will do something. Here is the main problem also , when I want to store login for some longer (some kind of session), I'd like to store it at userloginonline (in authorizate method), but after it leaves that method it stores null string! Also I've tested same thing in DBconnection class , in method getlogpw but It also didn't store it for any longer time.

I'm also giving here 2 other classes but they are kinda ussles and propably not related to the problem:

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;


public class Stageerr {
Stage stageerr;

public Stageerr(ActionEvent event){
    try {
        FXMLLoader newframe = new FXMLLoader(getClass().getResource("ErrorWindow1.fxml"));
        Parent root1 = (Parent) newframe.load();

        stageerr = new Stage();
        stageerr.setTitle("Error");
        stageerr.setScene(new Scene(root1));
        stageerr.show();

    } catch(Exception e){
        e.printStackTrace();
    }

}

public Stageerr(ActionEvent event,String errorstr){
    try {
        FXMLLoader newframe = new FXMLLoader(getClass().getResource(errorstr));
        Parent root1 = (Parent) newframe.load();

        stageerr = new Stage();
        stageerr.setTitle("Error");
        stageerr.setScene(new Scene(root1));
        stageerr.show();

    } catch(Exception e){
        e.printStackTrace();
    }

}
}

And Windowopener...:

public class windowopener {
Stage mainstage;
public windowopener(ActionEvent event,String fxmlname,String name) throws IOException {
    FXMLLoader newframe = new FXMLLoader(getClass().getResource(fxmlname));
    Parent root1 = (Parent) newframe.load();
    mainstage = new Stage();
    mainstage.setTitle(name);
    mainstage.setScene(new Scene(root1));
    mainstage.show();


    ((Node)(event.getSource())).getScene().getWindow().hide();



}


}

And Withouthide class:

public class Withouthide {
Stage stageerr;

public Withouthide(ActionEvent event,String fxmlname,String name){
    try {
        FXMLLoader newframe = new FXMLLoader(getClass().getResource(fxmlname));
        Parent root1 = (Parent) newframe.load();

        stageerr = new Stage();
        stageerr.setTitle(name);
        stageerr.setScene(new Scene(root1));
        stageerr.show();

    } catch(Exception e){
        e.printStackTrace();
    }

}
}

I also didn't drop here code for fxml files since there are like 8 of them and they are not so really important (I think so, If it would help you to find an answer for that I'd drop the code here). Also I'd like to notice that I'm using InteliJ and I've found really similar problem here on stack but it was not solved (Cannot store Object in List<Object> with method from package?). Also If you see any bad programmers habits in my code I'd love to hear any advices ;) and Thanks for your time!

Community
  • 1
  • 1
SigKillMe
  • 19
  • 1
  • 1
  • 8
  • You show that you're loading many fxml files (perhaps multiple times), so you have multiple controllers. (You only show one controller class, so maybe they are all the same class - that's a bad idea but it doesn't really make any difference here.) If you have multiple controllers, each one has it's own `userloginonline` field. Those fields won't all have the same value. Hard to really tell unless you can create a [MCVE] and [edit] your question to show it. – James_D Jan 17 '17 at 13:23
  • Well , your answer is propably right and is the answer I was looking for , because yeah , I use one controller class for multiple fxml files, and now I realized that when I have different window opened , it won't load my previous variable right..Do you know how to solve that problem without making major changes? Also I've put here all the classes I have here. The only things I didn't put are fxml files because I think they are no needed here and would only make this post less readable. – SigKillMe Jan 17 '17 at 14:46
  • I would certainly recommend using a different controller class for each different FXML file (else it just gets too difficult to track what is initialized in each controller). Either way, you need to share data among all the controllers. So I would create a class to hold the login status (perhaps has a `BooleanProperty` for logged in, a `StringProperty` for user name, etc etc). This class is a "model" for login status. Create *one* instance of that class and pass it to each controller when you load the FXML. You can look at http://stackoverflow.com/questions/14187963 for how to pass the data. – James_D Jan 17 '17 at 15:00
  • Thank you , I certanly did as you said ;) I used singleton pattern and create class with static methods and IT WORKS! Ps.yeah this controller is kind of mess , but it's my first time with JavaFx that's why :( – SigKillMe Jan 17 '17 at 16:38
  • Ugh. [Don't use the singleton pattern](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) (certainly not in this context). I'm glad it is working but you should really consider refactoring this as it will likely come back to bite you later if you don't. – James_D Jan 17 '17 at 16:42
  • Thanks for advice , will do definately ;) – SigKillMe Jan 17 '17 at 18:45

0 Answers0