提问人:Juliana Miranda 提问时间:5/21/2022 最后编辑:Juliana Miranda 更新时间:5/21/2022 访问量:370
getViewTreeObserver().addOnGlobalLayoutListener 上的 Android 空对象引用
Android null object reference on getViewTreeObserver().addOnGlobalLayoutListener
问:
在执行操作之前,我需要检查布局是否已完全膨胀,为此,我使用下面的代码,该代码具有一个信号量,该信号量会等待直到两个特定按钮膨胀。代码大部分时间都工作正常,但有时我收到致命异常错误:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“boolean java.util.ArrayList.add(java.lang.Object)”。有谁知道为什么以及如何解决它?下面是代码和完整日志:
final Semaphore semaphore = new Semaphore(0);
LayoutKBDReferencesHelper.instance().
getLayoutKBDReferences().getBtn0().
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
semaphore.release();
}
});
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
final Semaphore semaphore1 = new Semaphore(0);
LayoutKBDReferencesHelper.instance().getLayoutKBDReferences().getBtn1().
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
semaphore1.release();
}
});
try {
semaphore1.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
日志:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at android.view.ViewTreeObserver$CopyOnWriteArray.add(ViewTreeObserver.java:1181)
at android.view.ViewTreeObserver.addOnGlobalLayoutListener(ViewTreeObserver.java:550)
at com.example.layout.SampleLayout.showKBD(SampleLayout.java:1025)
at com.example.layout.SampleLayout.OutputCallbacks.Text(OutputCallbacks.java:108)
at com.example.layout.SampleLayout.Base.Text(SourceFile:5)
at com.example.layout.SampleLayout.LayoutTest(SourceFile)
at com.example.layout.SampleLayout.LayoutTest(SourceFile:4)
at com.example.layout.SampleLayout.LayoutTest(SourceFile:1)
at com.example.layout.SampleLayout.SampleLayout$4.run(SampleLayout.java:378)
at java.lang.Thread.run(Thread.java:764)
答: 暂无答案
评论
ViewTreeObserver.OnGlobalLayoutListener
onDestroy()