Kotlin Globalscope.launch中的RecyclerView出现问题
启动时,出现以下错误android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图Kotlin Globalscope.launch中的RecyclerView出现问题,kotlin,global-scope,Kotlin,Global Scope,启动时,出现以下错误android.view.ViewRootImpl$CalledFromErrorThreadException:只有创建视图层次结构的原始线程才能接触其视图 class FirstFragment : Fragment(){ private val TAG: String = "Information from app" lateinit var response:Response<Reqres> private la
class FirstFragment : Fragment(){
private val TAG: String = "Information from app"
lateinit var response:Response<Reqres>
private lateinit var post :Reqres
public lateinit var listus :List<databases>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
Log.i(TAG, "Info about onCreateView1")
val view = inflater.inflate(R.layout.fragment_first, container, false)
val recycle= view.findViewById<RecyclerView>(R.id.recyclerview)
recycle.layoutManager = LinearLayoutManager(activity)
GlobalScope.launch(Dispatchers.IO) {
response = App.getApi().getData().execute()
post=response.body()
listus = post.data
recycle.adapter = Recycleadapter(listus)
}
return view
}
classfirstfragment:Fragment(){
private val标记:String=“来自应用程序的信息”
lateinit var响应:响应
私有lateinit var post:Reqres
公共lateinit var listus:列表
覆盖创建视图(
充气器:布局充气器,容器:视图组?,
savedInstanceState:捆绑?
):查看{
//为该碎片膨胀布局
Log.i(标记“关于onCreateView1的信息”)
val视图=充气机。充气(R.layout.fragment_first,container,false)
val recycle=view.findviewbyd(R.id.recyclerview)
recycle.layoutManager=LinearLayoutManager(活动)
GlobalScope.launch(Dispatchers.IO){
response=App.getApi().getData().execute()
post=response.body()
listus=post.data
recycle.adapter=Recycleadapter(listus)
}
返回视图
}
使用lifecycleScope
而不是GlobalScope,并且不要更改调度程序。只将阻塞代码包装在withContext(Dispatchers.IO){}
中。您的其他功能应该留在lifecycleScope
的默认主调度程序上运行。谢谢。您的建议帮助了我。我的应用程序工作正常!