Group Group Group Group Group Group Group Group Group

Exception on Pet Companion app

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

@lgleason Can you please help with this when you get a chance? Thank you - much appreciated! :]

1 Like

Hello,

I’m surprised your getting that error message. When I test the code from the final project that does not have the GlobalScope.lanch above the if I’m not getting that error message. If anything those two extra lines should not care which thread they are on. since they are both attributes and are not instrumented to be retrieved on another thread etc… Were you running the final project when you ran into this or were you following along with the tutorial when this happened?

1 Like

Hey @lgleason,
I was following along. Maybe I didn’t copy the code correctly from the book. To be honest, I don’t remember even looking at the final project. I just fixed it and moved on the the next chapter.

Either way thank you.