Reputation: 281
I am working on an application in android. And I am trying to update data to UI from the background thread. However, it doesn't work for some reasons. Can any one splot the error or suggest any better solution? I used Thread to read data from the bluetooth socket and update the UI with RunOntheUI. Here is the code:
socket = belt.createRfcommSocketToServiceRecord(UUID_SECURE);
socket.connect();
stream = socket.getInputStream();
// final int intch;
Thread timer2 = new Thread() { // Threads - do multiple things
public void run() {
try {
// read data from input stream if the end has not been reached
while ((intch = stream.read()) != -1) {
byte ch = (byte) intch;
b1.append(ByteToHexString(ch) +"/");
decoder.Decode(b1.toString());
runOnUiThread(new Runnable() {
public void run()
{
// update the uI
hRMonitor.SetHeartRateValue((int) decoder.GetHeartRate());
}
});
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}};
timer2.start();
Upvotes: 0
Views: 70
Reputation: 30276
No. You MUST NOT do that. Never use another thread to update UI Thread, because UI Thread is not thread-safe
, it means : when you update your UI Thread, UI Thread doesn't stop working for you do some stuff.
And Android has a machism for this work. This is Asyntask
: it will create another thread and when need, it will has safe way to update UI Thread. If you want to more detail, Asyntask will drop a message to message queue of UI Thread.
Here is another link of my post about different Thread, Handler and Asyntask. Asyntask
Hope this help :)
Upvotes: 0
Reputation: 132972
use
Your_Current_Activity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
hRMonitor.SetHeartRateValue((int) decoder.GetHeartRate());
}
});
instead of
runOnUiThread(new Runnable() {
public void run()
{
// update the uI
hRMonitor.SetHeartRateValue((int) decoder.GetHeartRate());
}
});
Upvotes: 1