Greetings,
In chapter 13, I’m getting an android.view.ViewRootImpl$CalledFromWrongThreadException on the Pet Companion app. I’m not familiar with coroutines yet but I move the global scope call to the main thread above the if statement to fix it.
Here are the code snippets:
Before:
if (searchForPetResponse.isSuccessful) {
searchForPetResponse.body()?.let {
GlobalScope.launch(Dispatchers.Main) {
if (it.animals.size > 0) {
noResultsTextView?.visibility = INVISIBLE
viewManager = LinearLayoutManager(context)
companionAdapter = CompanionAdapter(it.animals, searchForCompanionFragment)
petRecyclerView = view?.let {
it.findViewById(R.id.petRecyclerView).apply {
layoutManager = viewManager
adapter = companionAdapter
}
}
} else {
noResultsTextView?.visibility = VISIBLE
}
}
}
} else {
noResultsTextView?.visibility = VISIBLE
}
After:
GlobalScope.launch(Dispatchers.Main) {
if (searchForPetResponse.isSuccessful) {
searchForPetResponse.body()?.let {
if (it.animals.size > 0) {
noResultsTextView?.visibility = INVISIBLE
viewManager = LinearLayoutManager(context)
companionAdapter = CompanionAdapter(it.animals, searchForCompanionFragment)
petRecyclerView = view?.let {
it.findViewById(R.id.petRecyclerView).apply {
layoutManager = viewManager
adapter = companionAdapter
}
}
} else {
noResultsTextView?.visibility = VISIBLE
}
}
} else {
noResultsTextView?.visibility = VISIBLE
}
}
Not sure if this is the best way to solve this since I’m new to coroutines