嗨,我正在从程序中从网络获取一些信息,其中包含协程。接收信息时,我更改了片段。在这种情况下,程序崩溃并且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()
}
更新:logcat:
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)
尝试一下,您需要使用findviewbyid
lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater!!.inflate(R.layout.some_fragment, container, false)
recyclerView = view.findViewById(R.id.rc)
return view
}
对您所有的元素都执行此操作,我以前曾遇到过此问题,并已通过此方法对其进行了修复
从您的堆栈跟踪来看,似乎progress.isIndeterminate = false
是错误的原因。似乎progress
尚未初始化。也许您忘记了findViewById()
或用于视图绑定的任何东西。