Reading and printing the data in this class is succesful, But accessing the value out of this returns null...
Based in your code I see you're following this example: Event Based Two Way Communication (if you are not then you should take a look). As its title says it's an event based way of read/write through serial port.
Having said this, I strongly suspect you're trying to do something like this:
XXX serialPortListener = new XXX();
int light = serialPortListener.send();
int lightStatus = serialPortListener.sendst();
It's most likely that send()
and sendst()
return null
or 0
because no SerialPortEvent
has happened yet when these methods are called. So if you're working in an event driven scenario then it makes sense keep in this framework. How? For instance implementing an Observer pattern:
1) Make XXX
class extend from Observable
and perform this little change:
public class XXX extends Observable implements SerialPortEventListener {
int[] val = new int[2];
public synchronized void serialEvent(SerialPortEvent oEvent) {
String storeId;
String status;
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
// all your code here
setChanged();
notifyObservers();
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
...
}
2) Another class has to implement Observer
interface:
public class MyObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
if(o instanceof XXX){
XXX observable = (XXX) o;
System.out.println("Light: " + observable.send());
System.out.println("Light status: " + observable.sendst());
}
}
}
3) Append a MyObserver
object to XXX
instance:
XXX serialPortListener = new XXX();
serialPortListener.addObserver(new MyObserver());
That's it. Every time a SerialPortEvent
is processed the observer will be notified and it will successfuly read the values.