why this code works?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("onCreate", Thread.currentThread().toString());
textView = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
HandlerThread thread = new HandlerThread("myHandlerThread");
thread.start();
mUiHandler = new Handler(thread.getLooper());
mUiHandler.post(new Runnable() {
@Override
public void run() {
Log.i("Thread: ", Thread.currentThread().toString());
Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
textView.setText("Hello Cats");
imageView.setImageResource(R.mipmap.ic_launcher);
}
});
}
i read from somewhere that the only thread that can communicate with UI objects is UI thread, or i miss something
i have some research but not found the answer yet, please help, thank you so much guys.
this is what i got from log
10-13 18:47:42.888 23841-23841/th.co.me.sampleapp I/onCreate: Thread[main,5,main]
10-13 18:47:42.891 23841-24041/th.co.me.sampleapp I/Thread:: Thread[myHandlerThread,5,main]
UPDATE 1
i tried this code from @nshmura and the error occurs it is so confusing to me now
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HandlerThread thread = new HandlerThread("myHandlerThread");
thread.start();
mUiHandler = new Handler(thread.getLooper());
mUiHandler.post(new Runnable() {
@Override
public void run() {
Log.i("Thread: ", Thread.currentThread().toString());
Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
textView.setText("Hello Cats");
imageView.setImageResource(R.mipmap.ic_launcher);
}
});
}
});
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.