Kacper Brachaczek Kacper Brachaczek - 27 days ago 9
Android Question

Dynamic display data TextView

I already got displayed data received from microprocesor via bluetooth. It sends me an 8-bit frame with actual Voltage and Temperature state every second.

The issue is the TextView doesn't displaying actual data. When app loads, the data is displayed and stays like that. One method to refresh data is to load app again.

I got handler and ConnectedThread which code I attach.

All the best from Poland.

bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
sb.append(readMessage);
int endOfLineIndex = sb.indexOf(";\r\n");

if (endOfLineIndex > 0) {
String dataInPrint = sb.substring(0, endOfLineIndex);
strDlugosc.setText(dataInPrint);
int dataLenght = dataInPrint.length();
strLenght.setText("ilość otrzymanych znakow =" + String.valueOf(dataLenght));

if (sb.charAt(0) == '9') {

String statusb = sb.substring(8,9);
String temperatura = sb.substring(21, 27);
String napiecie = sb.substring(12, 18);

status.setText("Status :" + statusb);
temp_1.setText("TEMPERATURA = " + temperatura + " *C");
nap_1.setText("NAPIECIE = " + napiecie + " V");


}
}
}


private class ConnectedThread extends Thread {
private final InputStream mmInStream;


//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;

try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
} catch (IOException e) { }

mmInStream = tmpIn;
}


public void run() {
byte[] buffer = new byte[1024];
int bytes;

// Keep looping to listen for received messages
while (!ConnectedThread.interrupted()) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();

} catch (IOException e) {

break;
}
}
}

Answer Source

I did it before. I used a timer to get data from BlueTooth socket every 1 second

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
     // get data from socket and set to text view here
    }

}, 0, 10000 /** milliseconds **/);