0

I have an Excel file that i load it in tableView the data of this file i load it in variable data, i want to pass this variable to another controller ControllerTwo to do some stuff on it but it returs a null pointer exception

any prposition will be appreciated

Main:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("guiOne.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 500, 500));
        primaryStage.show();
    }


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


ControllerOne:

public class ControllerOne implements Initializable {

    @FXML Pane pane;

    //-----------------Observable Data List-------------
    ObservableList<ObservableList<String>> observableDataList = FXCollections.observableArrayList();

    public List<List<String>> getData() {
        return data;
    }

    List<List<String>>  data;



    //-------------TABLE VIEW--------------------
    @FXML
    private TableView<ObservableList<String>> dataTableView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        //dataTableView.setItems(observableDataList);
    }

    //////////////////----LOAD DATA---////////////////////////
    public void loadData(ActionEvent event) throws IOException {
        //---------FILE CHOOSER
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open file");
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("XLSX files (*.xlsx)", "*.xlsx");
        fileChooser.getExtensionFilters().add(extFilter);
        File file = fileChooser.showOpenDialog(dataTableView.getScene().getWindow());
        //----------Get data from excel file
        data = readExcelFile(file.getPath());//


        //------------ADD TO OBSERVABLE
        for (int i = 1; i < data.size(); i++) {
            observableDataList.add(FXCollections.observableArrayList(data.get(i)));
        }

        //-------------FILL TABLE
        for (int i = 0; i < data.get(1).size(); i++) {
            int numCol = i;
            TableColumn<ObservableList<String>, String> column = null;
            if (i == 0) {
                column = new TableColumn<>("   ");

            }
            if (i != 0) {
                column = new TableColumn<>("g" + (numCol - 1));

            }
            column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().get(numCol)));
            column.setPrefWidth(75);
            dataTableView.getColumns().add(column);

        }
        dataTableView.setItems(observableDataList);


    }

    ////////////////---------READ EXCEL FILE------////////////////////////
    private List<List<String>> readExcelFile(String filePath) {

        List<List<String>> excelContent = new ArrayList<>();


        try (InputStream inputStream = new FileInputStream(filePath)) {
            DataFormatter formatter = new DataFormatter();

            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                List<String> tempList = new ArrayList();

                for (Cell cell : row) {
                    String text = formatter.formatCellValue(cell);
                    //tempList.add(text.length() == 0 ? "" : text);
                    tempList.add(text);
                }
                excelContent.add(tempList);
            }
        }
        catch (IOException | EncryptedDocumentException ex) {
            System.out.println(ex.toString());
        }
        return excelContent;
    }


    public void passToGuiTwo(ActionEvent event) {
        Parent root = null;


        try {
            root = FXMLLoader.load(getClass().getResource("guiTwo.fxml"));
        } catch (IOException e) {
            e.printStackTrace();
        }


        ((Stage)pane.getScene().getWindow()).setScene(new Scene(root, 200, 200));

    }
}

FXML of Controller One:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.Pane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<Pane fx:id="pane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ControllerOne">
   <children>
      <VBox prefHeight="303.0" prefWidth="600.0">
         <children>
            <Button mnemonicParsing="false" onAction="#loadData" prefHeight="25.0" prefWidth="173.0" style="-fx-background-color: black; -fx-background-radius: 0;" text="import file " textFill="RED">
               <VBox.margin>
                  <Insets bottom="20.0" left="200.0" top="20.0" />
               </VBox.margin>
               <font>
                  <Font name="Arial Black" size="16.0" />
               </font>
            </Button>
            <TableView fx:id="dataTableView" prefHeight="200.0" prefWidth="200.0">
               <VBox.margin>
                  <Insets left="10.0" right="10.0" />
               </VBox.margin>
            </TableView>
            <Button mnemonicParsing="false" onAction="#passToGuiTwo" prefHeight="25.0" prefWidth="580.0" text="Pass To guiTwo">
               <VBox.margin>
                  <Insets left="10.0" top="20.0" />
               </VBox.margin>
            </Button>
         </children>
      </VBox>
   </children>
</Pane>


ControllerTwo:

package sample;

import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.layout.AnchorPane;

import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class ControllerTwo implements Initializable {

   List<List<String>> d;

    public ControllerTwo() throws IOException {

    }




    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public void getDataFromOne(ActionEvent event) {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("guiTwo.fxml"));

        ControllerOne controller1 = loader.getController();
        d= controller1.getData();
    }
}


FXML of ControllerTwo:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.ControllerTwo">
   <children>
      <Button layoutX="181.0" layoutY="139.0" mnemonicParsing="false" onAction="#getDataFromOne" prefHeight="64.0" prefWidth="202.0" text="get DATA" />
   </children>
</Pane>

**ERROR: **

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8411)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:352)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:388)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:387)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
    ... 48 more
Caused by: java.lang.NullPointerException
    at sample.ControllerTwo.getDataFromOne(ControllerTwo.java:33)
    ... 58 more
  • Do it “the other way around”. That is, in controller 1, when you load the second FXML, get the reference to the second controller and call a method on it to initialize the data. – James_D Mar 28 '20 at 20:06
  • @James_D can you give me a similaire example – Asmaa MOHAMEDI Mar 28 '20 at 22:25
  • https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml – James_D Mar 28 '20 at 22:27
  • imake som changes in the methode that load the second FXML:`public void passToGuiTwo(ActionEvent event) { Parent root = null; try { root = FXMLLoader.load(getClass().getResource("guiTwo.fxml")); } catch (IOException e) { e.printStackTrace(); } FXMLLoader loader = new FXMLLoader(getClass().getResource("guiTwo.fxml")); ControllerTwo controller2 = loader.getController(); controller2.initializeData(data); ((Stage)pane.getScene().getWindow()).setScene(new Scene(root, 200, 200)); }` – Asmaa MOHAMEDI Mar 28 '20 at 22:38
  • when i'm debuging with the new code (look at the comment above) the variable controller2 is null – Asmaa MOHAMEDI Mar 28 '20 at 22:50
  • See the linked question. – James_D Mar 28 '20 at 23:11

0 Answers0