当我尝试在 Fragment 中加载 WebView 时,我在 Android 应用程序中遇到 NullPointerException。该错误具体发生在 WebViewClient 的 onProgressChanged() 方法中。这是堆栈跟踪的相关部分:
java.lang.NullPointerException at com.example.card.SettingsFragment.getBinding(SettingsFragment.kt:36) at com.example.card.SettingsFragment.access$getBinding(SettingsFragment.kt:34) at com.example.card.SettingsFragment$onViewCreated$1.onProgressChanged(SettingsFragment.kt:53)
这是代码片段:
class SettingsFragment : Fragment() {
private var _binding: FragmentSettingsBinding? = null
private val binding get() = _binding!!
private val TAG = "SettingsFragment"
private lateinit var webView: WebView
val url = "https://example.com"
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
webView = binding.webviewForDigiLocker
webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
Log.e(TAG, "$newProgress")
//here causing problem
binding.progressBar.progress = newProgress
if (newProgress == 100) {
binding.loader.visibility = View.GONE
binding.progressBar.visibility = View.GONE
}
}
}
webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
Log.e(TAG, "PageStarted")
binding.progressBar.visibility = View.VISIBLE
binding.loader.visibility = View.VISIBLE
}
}
webView.settings.javaScriptEnabled = true
webView.settings.allowContentAccess = true
webView.settings.domStorageEnabled = true
webView.isSaveEnabled = true
webView.loadUrl(url)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = FragmentSettingsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
Log.e(TAG,"DestroyView")
}
}
尝试访问绑定.progressBar和绑定.loader时,绑定对象似乎为空,导致NullPointerException。但是,我不确定为什么会发生这种情况,因为我已经在 onCreateView() 中正确初始化了绑定对象。在 OnDestroyView 中时我也将其设置为空
任何关于为什么会发生此错误以及如何解决该错误的见解将不胜感激。谢谢!
您所面临的 ProgressBar 为 null 的问题似乎与 Fragment 生命周期的处理以及尝试通过绑定访问 UI 元素的时间有关。确保在 Fragment 生命周期中的正确时间访问 UI 元素至关重要。
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
Log.e(TAG, "$newProgress")
// Check if binding is not null before accessing UI elements
binding?.let {
it.progressBar.progress = newProgress
if (newProgress == 100) {
it.loader.visibility = View.GONE
it.progressBar.visibility = View.GONE
}
}
}
这应该可以为您解决空问题。