0

I am developing a payment gateway of a vending machine. My gateway connects to the vending machine successfully using socket. I am able to receive messages on the required price successfully process it but sending back my approval messages to machines gives java.lang.NullPointerException . My UI is on JavaFX

below is my code on 1st Controller

@FXML
    public void handleButtonAction(ActionEvent event)throws UnknownHostException, IOException {
        LOGGER.info("Connect button Clicked"); 
        status.setWrapText(true);        
        status.appendText("Connect button Clicked \n");
        // getting localhost ip 
        InetAddress ip = InetAddress.getByName("localhost");        
          
        // establish the connection 
        s = new Socket(ip, ServerPort);
        status.appendText("connected to " + s.toString() + "\n" );
        LOGGER.info("connected to " +  s.toString() + "\n" );           
         
         //start a scanning thread
            receivemessage();         
    }

receive message method

public void receivemessage()
    {
         LOGGER.info("Receive message thread started"); 
         status.setWrapText(true);
         status.appendText("Receive message thread started \n");
        // readMessage thread 
        
        Thread readMessage = new Thread(new Runnable() 
        {
          // Platform.setImplicitExit(false); 
           
            public void run(){
                InputStream input = null;
                try {
                
                input = s.getInputStream();
                status.appendText("Scanning thread started.");

                //scanning always running
                while(true) {
                    
                    String dataString = ""; 
                    byte buffer[] = new byte[1024];
  
                    // read all received bytes
                    while (input.available() > 0) {
                        int i = input.read(buffer, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        dataString += new String(buffer, 0, i);
                    }
                    
                    if(!dataString.isEmpty()) {
                        status.appendText("Server respond: \"" +dataString +"\"");
                        LOGGER.info("Server respond: \"" +dataString +"\"");
                        
                        String VendRequest_input="External PC Plugin;Vend Request;add_on_variable=&required_price=50#";
                        try {
                            Thread.sleep(1000);       
                        } catch (InterruptedException ex) {
                            Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        final String data=dataString;
                        Platform.runLater(() ->{
                            try {
                                
                                loadPhoneInput(data);
                            } catch (IOException ex) {
                                Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        });
                        
                        
                         /*for (int x=0; x<result.length; x++) {
                            System.out.println(result[x]);
                            }*/
                        
                    }                       
                }
                
                } catch (IOException ex) {
                    Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                try {
                    input.close();
                } catch (IOException ex) {
                    Logger.getLogger(BritsConnectController.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
         }
        }); 
        
       readMessage.start();
    }
  
    public void loadPhoneInput( String dataString) throws IOException
    {
        
        //Parse String and Capture
        String Capture = dataString;
        String[] tokens = Capture.split("#");
        
        System.out.println(tokens.length);
        for(int i=0; i<tokens.length; i++)
        {
            String prefix = "External PC Plugin;Vend Request;add_on_variable=&required_price=";
            
            if(tokens[i].contains(prefix))
            {
                //fetch total Amount
                System.out.println(tokens[i]);
                String Command=tokens[i];
                String[] price = Command.split("&");
                String exact_Price=price[1]; //required_price=50
                String[] total_Amount =exact_Price.split("=");
                System.out.println();
                String totalAmount=total_Amount[1];
                //Load phone Input and Pass Prices
                FXMLLoader loader = new FXMLLoader(getClass().getResource("PhoneInput.fxml"));
                Parent root = (Parent) loader.load();
                //transfer totalAmount
                PhoneInputController phonecontoller=loader.<PhoneInputController>getController();
                phonecontoller.setDispenseAmount(totalAmount);
                //load phone input
                Stage stage=new Stage();
                Scene scene = new Scene(root);        
                stage.setScene(scene);
                stage.initStyle(StageStyle.UNDECORATED);
                stage.show(); 
                stage.centerOnScreen();
                stage.setAlwaysOnTop(true);
                //close current pane
                //ConnectorStage = (Stage)ConnectorPane.getScene().getWindow();// pane you are ON
                //ConnectorStage.hide();
            }            
        }        
    }

Send approval message method

@FXML
public void sendVendronApproveResponse() 
{
    System.out.println("Sending Initiated....");
    String msg ="External PC Plugin;Vend Request Respond;status=approve#";
    try {
        PrintWriter output= new PrintWriter(s.getOutputStream(),true);
        output.printf(msg);
        output.flush();
        status.appendText("\nSending to server: " +msg);
    } catch (Exception e) {
       LOGGER.info(e.toString());
       e.printStackTrace();
       System.out.println( e.getCause());
    }
}

This is code on second controller calling send message

private  void postUsingRawJSON(WebTarget target) throws IOException {
        
        String payment = paymentUtil.createPaymentInJSON(phoneNumberInput
                  , amountInput
                  , "1");
       
        ProviderResponse response = target.request()
                  .post(Entity.entity(payment, MediaType.APPLICATION_JSON)
                            , ProviderResponse.class);
        System.out.println(response.getCode());
        
        //Response message option to Vendron
        String Vend_Request_Respond_APPROVE="External PC Plugin;Vend Request Respond;status=approve#";
        String Vend_Request_Respond_DENIED="External PC Plugin;Vend Request Respond;status=denied#";
        
        String code=response.getCode();
        switch (code){
            case "0":
            {
            //send Vendron Dispense Command
            try 
            {                
            FXMLLoader loader1 = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
            BritsConnectController britsContoller = loader1.getController();
            britsContoller.sendMessage(Vend_Request_Respond_APPROVE);
            }            
            catch (Exception ex) {
            ex.getCause();
            ex.printStackTrace();
            }
                
            FXMLLoader loader = new FXMLLoader(getClass().getResource("successTransaction.fxml"));
            Parent root = loader.load();
            Stage stage=new Stage();
            Scene scene = new Scene(root);        
            stage.setScene(scene);
            stage.initStyle(StageStyle.UNDECORATED);
            stage.show(); 
            stage.centerOnScreen();
            stage.setAlwaysOnTop(true);
            confirmStage = (Stage)confirmPane.getScene().getWindow();// pane you are ON
            confirmStage.hide();
            
           
            
            PauseTransition delay = new PauseTransition(Duration.seconds(10));
            delay.setOnFinished( event -> stage.close() );
            delay.play();
            break;
            }
            
           
                
        }
        //get the new customer
        //getCustomerById(target, response);

    }
DENNIS KITHINJI
  • 217
  • 2
  • 14
  • When trying to call sendMessage – DENNIS KITHINJI Jun 28 '20 at 12:12
  • That sounds like britsContoller is null. Consider making a class that handles sending, then other classes can delegate to it. Also, in a question like this, it's usually helpful to share the info from your stack trace that shows what line this is occurring on. – Don Branson Jun 28 '20 at 12:18
  • Stack trace error is: java.lang.NullPointerException at vendronbritsclientui.confirmPhoneController.postUsingRawJSON(confirmPhoneController.java:125) at vendronbritsclientui.confirmPhoneController.handlebuttonOKClick(confirmPhoneController.java:98) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) – DENNIS KITHINJI Jun 28 '20 at 12:20
  • @DonBranson how can britsController be null I have instantiated it correctly – DENNIS KITHINJI Jun 28 '20 at 12:21
  • 1
    @DENNISKITHINJI No, it’s null. You haven’t loaded the FXML, so the FXMLLoader will not have instantiated the controller. Even if you do load it, your call to `sendMessage()` won’t do anything meaningful, because it will be updating a UI that’s not displayed. – James_D Jun 28 '20 at 12:31
  • Just saying for future reference, when you ask a question on SO about an exception, people will want to know what line it occurred on to help with your question. Including that will get you a faster response, and probably more help. – Don Branson Jun 28 '20 at 17:44

0 Answers0