0

I am trying to get the username after logged in from the text field and pass to another scene by instantiated a new object of the "logincontroller" class, but it shows the "NullPointerException" error. In the first class "Logincontroller" I managed to print the username by calling the method "CurrentUsername()" , the same method is called in another class "AddDocument" but doesn't work . First , is it correct to store the username in from the username text field and access it in another scence ? is there a better way to access username in another scence after logged in ? I wonder, and I would be very gratefull if anyone can help me.

public class LoginController implements Initializable {
@FXML
    private TextField txtUsername;
    @FXML
    private TextField txtPassword;
    @FXML
    .
    .
    .
     @FXML
    public void loginaction (ActionEvent event){
        try {

            if (this.loginmodel.isLogin(this.txtUsername.getText(),this.txtPassword.getText(),((Option)this.RoleSelection.getValue()).toString())){

                Stage stage = (Stage)this.btnLogin.getScene().getWindow();
                stage.close();

                switch (((Option)this.RoleSelection.getValue()).toString()){

                    case "Employee" :
                        EmployeeLogin ();
                        break;
                    case "Student":
                       StudentLogin();
                        break;
                    case "Admin":
                        AdminLogin();
                        System.out.println(CurrentUsername()); // Here it has value and shows the username 
                        break;
                }

            }

            else {this.loginStatus.setText("Der Benutzername oder das Kenntwort ist nicht Korrekt");}
        }
        catch (Exception localException){
            // System.out.print("test failed");
        }
    }


   public String CurrentUsername() {
             String username = txtUsername.getText();
              return  username;
    }

}



   public Class AddDocument {

        @FXML
        private TextField DocumentId;
        @FXML
        private TextField DocumentName;
        @FXML
        private TextField Date;
          .
          .
          .
        // for the username I created a new object from the class where there is the text field "txtUsername.getText()" 

    public static void main(String[] args) {
           LoginController loginController = new LoginController ();

          String User = loginController.CurrentUsername();

          System.out.println(User); // here it it doesn't show the value,  but an exception Caused by: java.lang.NullPointerException

        }

       }
Jovani
  • 3
  • 1
  • 3
    Hello. Welcome to SO. First, if you're new to Java programming, I suggest you to take a look to [Learning the Java Language](https://docs.oracle.com/javase/tutorial/java/TOC.html). Then, `NullPointerException` is a very common exception when you're coding with Java. I suggest you to take a look to [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). – Mickael Dec 03 '18 at 17:03
  • please attach a stack trace – slavik Dec 29 '18 at 01:08

3 Answers3

2

I feel txtUsername is null due to which you are facing NPE.

How and where you are setting txtUsername?

Try changing your method CurrentUsername() to,

public String CurrentUsername() {
    if (txtUsername != null) {
        return txtUsername.getText();
    else {
        return null;
    }
}

This way at least you won't have NPE. Then see where and how to set txtUsername.

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
  • Thank you PushoesH Kumar Rajwasnshi , Your solution help me to avoid the NPE, but still the value from textfeild is null. Do you have any idea why is that ? The same method able to print the current username in the Loggincontroller class . – Jovani Dec 03 '18 at 17:12
  • @Jovani: I am new to javafx but I think, when your LoginController class is invoked using javafx framework, then `txtUsername` and `txtPassword` fields must be getting initialized due to which they get seeded with some passed values and in that case you don't get NPE. But when you are executing your code with `main` method, those values remain null and you get NPE. The only way I think how you can set some values in those variables is, you implement a setter and in `main` method, after you create LoginController object, you call the setter and initialize it with whatever username you want to. – Pushpesh Kumar Rajwanshi Dec 03 '18 at 20:44
  • Like this `public void setTxtUsername(TextField txtUsername) { this.txtUsername = txtUsername; } public void setTxtPassword(TextField txtPassword) { this.txtPassword = txtPassword; }` and then in main method do this `LoginController loginController = new LoginController(); loginController.setTxtUsername(new TextField("testuser")); loginController.setTxtPassword(new TextField("testpwd"));` This way both of these variables will no longer remain null. – Pushpesh Kumar Rajwanshi Dec 03 '18 at 20:47
  • Thank you for your help again. Unfortunatelly , this time it hasn't work because I think the probleme is the ... loginController.setTxtUsername (new TextField("testuser")). It pass the Textfield type but in the new class I wanted the String value from the previous class ( Username) . – Jovani Dec 04 '18 at 06:10
  • @Jovani: Yes, the way I told you to do was just so you don't get null values leading to NPE. For passing values from previous class, the flow needs to be followed. – Pushpesh Kumar Rajwanshi Dec 04 '18 at 06:17
1

You haven't instantiated either of the TextField objects, therefore when you call a method on the object 'txtUsername' from within the CurrentUsername method, a NullPointerException is thrown.

One solution to your problem could be to instantiate the declared objects in a constructor for the LoginController class, such as:

public LoginController() {
    txtUsername = new TextField();
    txtPassword = new TextField();
}
Andy Shearer
  • 177
  • 2
  • 13
0

You are calling the controller, and then inmediately calls for the user, wich is null.

 LoginController loginController = new LoginController ();

 String User = loginController.CurrentUsername();

Edit:

I would just create a User class with the attributes, getters and setters and instantiate it from the Main class

public class Person {
    private String userName;
    private String someUsefulValue;

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getSomeUsefulValue() {
        return someUsefulValue;
    }
    public void setSomeUsefulValue(String someUsefulValue) {
        this.someUsefulValue = someUsefulValue;
    }
    @Override
    public String toString() {
        return "Person [userName=" + userName + ", someUsefulValue=" + someUsefulValue + "]";
    }

Then, in your main class, use it:

Person user = new Person();

    public String getCurrentUser() {
        return user.getUserName();
    }

    public void setUser(Person p) {
        this.user = p;
    }

Inside your Login controller, you need to have a reference to the mainApp, something like:

  // Reference to the main application.
    private MainApp mainApp;


     /**
     * Called to give a reference back to itself.
     */
    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }

When you are loading the Controller and the FXML, you set the mainApp reference:

LoginController controller = loader.getController();
controller.setMainApp(this);

Finally, when you log in your app, if it's OK, just store the User in the mainApp User:

    Person loginUser = new Person();
    loginUser.setUserName(txtUserName.getText());
    loginUser.setSomeUsefulValue(txtBlablabla.getText());
    mainApp.setUser(loginUser);

That's it, now you can call the User data from anywhere using the getCurrentUser() in the main Class.

I hope this can help you.

gonzaloan
  • 371
  • 2
  • 13
  • Thank you for the help. Since there is no global varaible in Java (may be I am wrong) , but it would be more helpfull if you show me how to do that . Thank you again. – Jovani Dec 04 '18 at 05:50