提问人:Viacheslav Khailenko 提问时间:11/2/2023 最后编辑:Viacheslav Khailenko 更新时间:11/2/2023 访问量:30
当我快速重新打开我之前的片段时,getBinding 返回 null (NullPointerException)
When I quickly reopen my previous fragment getBinding return null (NullPointerException)
问:
我的getBinding有问题。我的BaseFragment实现在这里:
private var _binding: T? = null
protected val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
当我意识到这种情况时,问题: 片段 1 ->片段 2 ->快速返回片段 1 ->然后出现 NullPointerException
如果我在onDestroyView中删除它就可以了,但它打开了内存泄漏的可能性。_binding = null
所以我的问题是为什么会出现这个异常?我的绑定每次都应该在 onCreateView 中初始化
UPDT:
以下是带有错误的完整日志:
Process: com.***.***, PID: 23789
java.lang.NullPointerException
at com.android.*.ui.webview.QuoteFragment.getBinding(QuoteFragment.kt:23)
at com.android.*.ui.webview.QuoteFragment.access$getBinding(QuoteFragment.kt:20)
at com.android.*.ui.webview.QuoteFragment$WebClient.onPageStarted(QuoteFragment.kt:109)
at WV.nZ.c(chromium-TrichromeWebViewGoogle6432.aab-stable-599311133:16)
at WV.V6.handleMessage(chromium-TrichromeWebViewGoogle6432.aab-stable-599311133:505)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:210)
at android.os.Looper.loop(Looper.java:299)
at android.app.ActivityThread.main(ActivityThread.java:8293)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)
答:
0赞
Tieria
11/28/2023
#1
getBinding 上出现 nullpointer 的原因,您可能正在使用 或 .handler.postDelay
snackbar
当您按下后退按钮时,Handler、Snackbar、Animation 或 CountdownTimer 仍在工作,绑定将崩溃。
为避免这种情况,您需要在关闭 fragment 时取消它们。例如:
private val handler = Handler(Looper.getMainLooper())
private lateinit var runnable: Runnable
runnable = Runnable {
//do your delay job
}
handler.postDelayed(runnable, 600)
//onStop and/or Back pressed add this code
if (this::runnable.isInitialized) {
handler.removeCallbacks(runnable)
}
评论
0赞
Viacheslav Khailenko
11/29/2023
谢谢。你是对的,那是我的问题。谢谢
评论