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:

    Button.setOnClickListener(v -> {
    getWhichLandingShows();         // Here I make the retrofit call

    if (mGoToNewLandingPage)
        return LandingSaleV3Fragment.newInstance();
    else
            return NewLandingSaleFragment.newInstance();
});

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

This was my last try:

private void getWhichLandingShowSync() {
    InteractionServices interactionServices = RestServices.getInteractionServices();
    Call<GetLandingResponse> call = interactionServices.getLandingPage();
    try {
        call.execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

public class BackgroundService extends IntentService {
    private static final String TAG = "NewLpIntentService";

    public BackgroundService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        InteractionServices interactionServices = RestServices.getInteractionServices();
        Call<GetLandingResponse> call = interactionServices.getLandingPage();
        try {
            call.execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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