嗨,我在我的程序中使用协程从 Web 获取一些信息接收信息时我更改了 fragment 在这种情况下,程序崩溃并且 Null 错误采用以下选项
progress.isIndeterminate = false
adapter = CircularAdapter(itemsData, this@CircularFragment)
rc.adapter = adapter
adapter.notifyDataSetChanged()
swipe_refresh.visibility = View.VISIBLE
lyt_progress.visibility = View.GONE
swipe_refresh.isRefreshing = false
这是我的代码,我什至取消了 OnDestroyView 中的作业,但仍然出现错误
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
launch {
val operation = async(Dispatchers.IO) {
try {
...
for (myTable in table) {
val rows: Elements = myTable.select("tr")
activity?.runOnUiThread{
progress.isIndeterminate = false
}
for (i in 1 until rows.size) {
progress.progress = i
itemsData.add(...)
}
}
}catch (e: Exception){
activity?.runOnUiThread{
val navController = Navigation.findNavController(activity!!, R.id.nav_host_fragment)
navController.navigate(R.id.noVPNFragment)
}
}
}
operation.await() // wait for result of I/O operation without blocking the main thread
// update views
activity?.runOnUiThread{
adapter = CircularAdapter(itemsData, this@CircularFragment)
rc.adapter = adapter
adapter.notifyDataSetChanged()
swipe_refresh.visibility = View.VISIBLE
lyt_progress.visibility = View.GONE
swipe_refresh.isRefreshing = false
}
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
override fun onDestroyView() {
super.onDestroyView()
job.cancel()
}
更新:
日志猫:
02-21 12:52:48.268 16218-16218/ir.mahdi.circulars.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: ir.mahdi.circulars.test, PID: 16218
java.lang.IllegalStateException: progress must not be null
at ir.mahdi.circulars.Fragments.CircularFragment$getCirculars$1$operation$1$1.run(CircularFragment.kt:118)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
最佳答案
从您的堆栈跟踪看来,progress.isIndeterminate = false
是错误的原因。看起来像 progress
尚未初始化。也许你忘了findViewById()
或者您用于 View 绑定(bind)的任何东西。
关于android - 在 kotlin 中更改 fragment 获取 IllegalStateException 不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60335427/