I am trying to pass the ByteArrayOutputStream asciiStream from TestButtonHandler to the connect method. I get the array I want from the output of the button action, but when it comes to
byte[] b = asciiStream.toByteArray();
in the connect method, it gets a null pointer exception, Why is it not passing the array and how do I fix it? thx
public class MonitorView2 extends JFrame {
static SerialPort serialPort;
ByteArrayOutputStream asciiStream;
public MonitorView2() {
super("Monitor View 2");
JPanel pane = new JPanel();
setContentPane(pane);
JButton testButton = new JButton("Test Comm On");
pane.add(testButton);
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
class TestButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Test button action works!");
try
{
String a = "33, 48, 48, 66, 67, 78, 49, 13"; //comm on;
asciiStream = new ByteArrayOutputStream();
byte[] buf = a.getBytes();
asciiStream.write(buf);
System.out.println("Buffer as a string");
System.out.println(asciiStream.toString());
System.out.println("Into array");
byte[] b = asciiStream.toByteArray();
for (int i=0; i<b.length; i++) {
System.out.print((char) b);
}
}
catch (Exception ex)
{
System.out.println("Exception has been thrown :" + ex);
}
}
}
testButton.addActionListener( new TestButtonHandler());
}
public void connect ( String portName ) throws Exception {
String defaultPort = "/dev/ttyS0";
String asciiString;
Charset asciiCharset = Charset.forName("US-ASCII");
CharsetDecoder decoder = asciiCharset.newDecoder();
byte[] b = asciiStream.toByteArray();
//byte h[] = {33, 48, 48, 66, 67, 78, 49, 13}; //comm on
ByteBuffer asciiBytes = ByteBuffer.wrap(b);
CharBuffer bChars = null;
try {
bChars = decoder.decode(asciiBytes);
} catch (CharacterCodingException e) {
System.err.println("Error decoding");
System.exit(-1);
}
System.out.println(bChars);
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
out.write(b);
out.flush();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}