Skip to content
Advertisement

How to make a Retrofit call Synchronously without getting Main Thread Exception?

I’m facing an issue here, and I need some help.

In this application, we make Retrofit calls in the UI thread – right in the Activity -, this means that we don’t have a good architecture (i know).

The problem I’m facing, is that i need to make an Synchronous GET when the user click a button, and the GET will give me which fragment the user will be redirected, and i need to wait the response of the web service.

Like this:

JavaScript

I need a method that works, because i already tried everything, and I always get a MainThreadException.

This was my last try:

JavaScript

I already tried to put the Retrofit call in a separated class that extends IntentService, like this, but without success:

JavaScript

Advertisement

Answer

Using call.execute() is not a good idea in your case. It runs the request on the current thread. You could use call.enqueue(callback) and then show a progressbar. The request runs on a background thread and once you get the callback on the current thread, navigate to other fragments when onResponse callback is successful.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement