There are so many things wrong with the following code, but yet no errors and shown/given.
- btn3.setText(“fud”); should throw an NullPointerException. It doesn’t.
- I should not be allowed to modify UI elements from a non UI thread. I can and Android doesn’t complain about it.
What is going on here?
public class TestApp1Activity extends Activity {
private static final String TAG = TestApp1Activity.class.getSimpleName();
private Button btn1, btn2, btn3;
private ExecutorService threadPool;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
threadPool = Executors.newFixedThreadPool(4);
threadPool.submit(new Runnable() {
@Override
public void run() {
btn3.setText("fud"); // should give a NullPointerException. Doesn't only stops execution.
btn2.setText("From pool"); // shouldn't be able to touch UI comps from non-UI thread
}
});
new Thread(new Runnable() {
@Override
public void run() {
Log.i(TAG, "Before setting text on btn");
btn1.setText("From thread"); // shouldn't be able to touch UI comps from non-UI thread
Log.i(TAG, "After setting text on btn");
// So below actually throws the error I wanted.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.cox1);
imageView.setImageBitmap(bm);
}
}).start();
}
}
EDIT: Since I’m getting bad answers, let me answer my own questions.
- The ExecutorService.submit wraps the Runnable in a try/catch. If any errors are thrown, the are quietly discarded. This is terribly design by the Android team…gezzz
- So apparently you can modify some view components from another thread. Just not all of them.
1) The ExecutorService.submit wraps the Runnable in a try/catch. If any errors are thrown, the are quietly discarded. This is terribly design. Never should an error be quietly suppressed.
2) So apparently you can modify some view components from another thread. Just not all of them. The component just sets it’s properties and on the next onDraw the component is repainted. You can actually do this with a lot of components, but the Android team says “you could get unexpected results.” So avoid it.