[Solved] java – string return method is called before any value is assigned to string


It seems pretty logical to me:

You have a first event handling method execution in the EDT which gets the firmware version and then gets the port reader. Getting the firmware version causes an event to be received, in a different thread (and thus in parallel to the execution of portsMethod() in the EDT).

The event handling code invokes SwingUtilities.invokeAndWait(). This call thus waits for the first event handling methd to complete, and then appends the received string to sbPortReaderString. This append is thus done after the portsMethod has completed.

The serial port offers an event-based mechanism. I would simply use it to propagate the event to one or several listeners in the EDT:

// accessed only from the EDT
private List<MyPortListener> portListeners = new ArrayList<MyPortListener>();

public void addMyPortListener(MyPortListener listener) {
    portListeners.add(listener);
}

public void removeMyPortListener(MyPortListener listener) {
    portListeners.remove(listener);
}

... 

    @Override
    public void serialEvent(SerialPortEvent spe) {
        ...
        final String receivedString = ...;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                for (MyPortListener listener : portListeners) {
                    listener.stringReveivedFromSerialPort(receivedString);
                }
            }
        });
    }

Side note: your code is hard to understand mainly because your variables and methods are badly named.

7

solved java – string return method is called before any value is assigned to string