0

When I launch, I have this error android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

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
    }
  • Use `lifecycleScope` instead of GlobalScope, and don't change the dispatcher. Wrap only the blocking code in `withContext(Dispatchers.IO) { }`. Your other functions should be left to run on the default Main dispatcher of `lifecycleScope`. – Tenfour04 Apr 21 '21 at 20:07
  • Thank you. Your advice helped me. My app works! – fartita Apr 22 '21 at 11:11

0 Answers0