I'm sending a message to a Handler which is associated to it's own Thread. In the handleMessage method I try to update the UI with the content of the message using runOnUiThread. This works fine if take the message obj parameter from handleMessage and assign it to a new final variable. But if I don't use this assignment and take msg.obj directly in the runnable the obj variable is null even though the msg reference is having the same id when checking the msg reference passed to handleMessage before calling runOnUiThread.
Why is that happening?
This is working:
bt01.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Message msg = new Message();
msg.obj = new Data("Hi im the message");
mHandler.sendMessage(msg);
}
});
class LooperThread extends Thread {
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(final Message msg) {
final Object messageString = msg.obj;
runOnUiThread(new Runnable() {
@Override
public void run() {
tv01.setText(((Data)messageString).getMessage());
}
});
}
};
Looper.loop();
}
}
This is not working:
public void handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv01.setText(((Data)msg.obj).getMessage());
}
});
}