I want to store the data received from serial port in a string variable that will be accessed in another class.
I wrote up code that prints the data received from com port but when the variable is accessed out of the method it returns null..
Please help me out.. I am using RxTx library for this.
public class ProtocolImpl implements Protocol {
byte[] buffer = new byte[1024];
int tail = 0;
public String message;
public void onReceive(byte b) {
// simple protocol: each message ends with new line
if (b=='\n') {
onMessage();
} else {
buffer[tail] = b;
tail++;
}
}
public void onStreamClosed() {
onMessage();
}
/*
* When message is recognized onMessage is invoked
*/
private void onMessage() {
if (tail!=0)
{
// constructing message
message = getMessage(buffer, tail);
//rmess = message;
System.out.println("RECEIVED MESSAGE: " + message);
if ("KITM".equalsIgnoreCase(message)) {
CommPortSender.send(getMessage("OK"));
}
tail = 0;
}
}
public String rmess() /*this method is returning null.. please help me out*/
{
if (tail!=0) {
message = getMessage(buffer, tail);
}
return message;
}
// helper methods
public byte[] getMessage(String message) {
return (message).getBytes();
}
public String getMessage(byte[] buffer, int len) {
return new String(buffer, 0, tail);
}
}
You are using an instance variable
message. There is one instance of this variable for eachProtocolImplobject. Presumably theProtocolImplobject on whichonMessageis called is a differentProtocolImplobject on whichrmessis called.The easy fix is just to make
messagea static variable so that there is only one instance of that variable in the whole program. Be careful, though, this can cause some subtle problems like synchronization and object independence. A better solution is to make sure you are using the sameProtocolImplobject to call bothonMessageandrmess.