Hvordan kan jeg hente data fra SimpleRead classen
Jeg bruger følgende class til at læse fra serial portenimport java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements SerialPortEventListener {
private static final String SERIALPORT = "COM1";
private CommPortIdentifier portId;
private Enumeration portList;
public InputStream inputStream;
private SerialPort serialPort;
public static String data;
public SimpleRead(){
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
//System.out.print("test");
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(SERIALPORT)) {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
inputStream = serialPort.getInputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
//set config.
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
//data is available - read it!
byte[] readBuffer = new byte[8];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
data = new String(readBuffer);
System.out.print(data);
System.out.print("ja ja");
} catch (IOException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
men problem er at når jeg prøver at hente String data i en anden classe som
myclass{
SimpleRead read = new SimpleRead();
void getData(){
String Data1 = read.data;
}
}
får jeg bare null. hvor bliver min data af?
