Firu
Firu

Reputation: 199

Null pointer exception on Initialize second controller class from first controller class

I am trying to access initialize method of another calss from a different class.But I am getting nullpointer Exception while returning ctroller

THis is the code I am trying to call from my second calss.

    Line1-        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/src/myjavfxapp/controller/EditClientDetails.fxml"));
    Line 2-        EditClientDetailsController fooController = (EditClientDetailsController) fxmlLoader.getController();
      Line3-       fooController.initialize(null, null);

I am getting null pointer exception at line number 3.

Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:75)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:279)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1435)
    ... 44 more
Caused by: java.lang.NullPointerException
    at myjavfxapp.controller.NewUserController.saveNewuser(NewUserController.java:167)
    ... 54 more

My Intention is to initialize the "EditClientDetails.fxml" fields from different controller class.

Please point out if i missed anything.

Upvotes: 0

Views: 1690

Answers (1)

Jitendra Pareek
Jitendra Pareek

Reputation: 637

Try the below example it working fine, you have to use load() function of FxmlLoader class.

public class Xxx extends Application {

  @Override
  public void start(Stage stage) throws Exception {

    //Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));     
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
    Parent root = (Parent)loader.load();          
    Scene scene = new Scene(root);        
    stage.setScene(scene);
    stage.show();

    SampleController controller = (SampleController)loader.getController();

  }

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

Upvotes: 1

Related Questions