gpt4 book ai didi

android - 没有抛出 NullPointerException

转载 作者:太空狗 更新时间:2023-10-29 13:37:15 24 4
gpt4 key购买 nike

以下代码有很多错误,但没有显示/给出错误。

  1. btn3.setText("fud");应该抛出 NullPointerException。它没有。
  2. 不应允许我从非 UI 线程修改 UI 元素。我可以,Android 也不会提示。

这是怎么回事?

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();
}
}

编辑:因为我得到了不好的答案,让我回答我自己的问题。

  1. ExecutorService.submit 将 Runnable 包装在 try/catch 中。如果抛出任何错误,它们将被悄悄丢弃。这是 Android 团队的出色设计...gezzz
  2. 显然您可以从另一个线程修改一些 View 组件。只是不是全部。

最佳答案

1) ExecutorService.submit 将 Runnable 包装在 try/catch 中。如果抛出任何错误,它们将被悄悄丢弃。这是非常棒的设计。绝不应该悄悄地抑制错误。

2) 显然您可以从另一个线程修改一些 View 组件。只是不是全部。该组件只是设置它的属性,并在下一个 onDraw 上重新绘制该组件。你实际上可以用很多组件来做到这一点,但 Android 团队说“你可能会得到意想不到的结果”。所以避免它。

关于android - 没有抛出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com