启动片段的背景线程时,应用会随机崩溃
我有此片段的代码:
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtAngle = view.findViewById(R.id.textView_angle);
updateTextThread = new Thread(new Runnable() {
@Override
public void run() {
while (threadRunning) {
txtAngle.setText("1");
}
}
});
threadRunning = true;
updateTextThread.start();
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
threadRunning = false;
}
该应用在第一次导航到此片段时工作正常,但是如果我返回主页并再次导航到此片段,则该应用程序有30%的机会崩溃,投掷> java.lang.nullpoInterException:尝试调用
null对象参考线的虚拟方法'int android.text.layout.getWidth()'。我尝试使用setText
line的null对象参考thread.interrupt()
停止线程,但它不起作用。
那么是什么原因导致坠机事故,我该如何解决呢?
I have this code for my fragment:
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
txtAngle = view.findViewById(R.id.textView_angle);
updateTextThread = new Thread(new Runnable() {
@Override
public void run() {
while (threadRunning) {
txtAngle.setText("1");
}
}
});
threadRunning = true;
updateTextThread.start();
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
threadRunning = false;
}
The app works fine the first time I navigate to this fragment, but if I return to the main page and navigate to this fragment again, the app has a 30% chance to crash, throwing java.lang.NullPointerException: Attempt to invoke virtual method 'int android.text.Layout.getWidth()' on a null object reference
for the setText
line of the thread. I tried to use Thread.interrupt()
to stop the thread but it didn't work.
So what caused the crash and how can I solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在此处注意两件事:
:
使用线程安全变量,例如atomicicboolean或volatile boolean for
thread> threadrunning < / code> var ...和双检查锁定或a 锁定为了验证var的值,
您无法保证更新线程循环在更改setText方法之前不会在更改螺纹式var值时……
也最好调用super。 OnDestroyView()在OnDestroyView方法的末尾。
您可以做什么:
使用以下可能性之一(而不是详尽)访问TextView更新到主线程,
You should take care ot two things here :
What you should do :
use thread safe variables like AtomicBoolean or a volatile boolean for the
threadRunning
var... and a double checked locking or a Lock for verifying the value of the varwithout this you have no guarantee that you update thread loop is not before the setText method when changing the threadRunning var value...
also, you'd better call super.onDestroyView() at the end of the onDestroyView method.
What you could do :
Dispatch the TextView update from the update thread to the main thread using one of the following possibility (not exhaustive)