Skip to content Skip to sidebar Skip to footer

Retrofit 2 Error: Networkonmainthreadexception

I'm trying to do a synchronous request to my server in Android. (Code works flawlessly in a plain Java project) I know that sync requests shouldn't be done on the main thread, so I

Solution 1:

Instead of starting a new thread yourself, Retrofit can automatically do requests on a separate thread. You can do this by calling enqueue();.

Call<MapApiCall> call = api.getDurationJson(foo);

call.enqueue(newCallback<MapApiCall>() {
       @OverridepublicvoidonResponse(Call<MapApiCall> call, Response<MapApiCall> response) {
           //Do something with response
       }

       @OverridepublicvoidonFailure(Call<MapApiCall> call, Throwable t) {
           //Do something with failure
       }
   });

If you want synchronous requests use execute() within your seperate thread:

Call<MapApiCall> call = api.getDurationJson();  
MapApiCall apiCall = call.execute().body();  

If you, for some reason, want to disable the NetworkOnMainThreadException without using threads use:

StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

However, this is really not recommended, if you don't know what StrictMode does, do NOT use it.

Solution 2:

Your problem is that createRetrofitAdapter method was called on the main thread. That's where you were building a new Retrofit instance, but it absolutely cannot be done on the UI thread. The simplest shortcut is to do it in an AsyncTask.

Post a Comment for "Retrofit 2 Error: Networkonmainthreadexception"