Search code examples
javarxtx

I want to store the data received from serial port in a string variable that will be accessed in another class


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);  
    }  
}

Solution

  • You are using an instance variable message. There is one instance of this variable for each ProtocolImpl object. Presumably the ProtocolImpl object on which onMessage is called is a different ProtocolImpl object on which rmess is called.

    The easy fix is just to make message a 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 same ProtocolImpl object to call both onMessage and rmess.