2016-02-18 217 views
14

我正在使用Retrofit 2來獲取json並將其解析爲POJO。我的目的是獲得該對象的一個​​值。Retrofit - android.os.NetworkOnMainThreadException

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' 
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' 

我的REST客戶端:

public interface MyClient { 

    @GET("/part1/part2") 
    Call<MyItem> getMyItem(@Query("param1") String param1, 
               @Query("param2") String param2, 
               @Query("param3") String param3); 

} 

Here我發現很棒很棒的工具來創建服務:

public class ServiceGenerator { 

    public static final String API_BASE_URL = "http://my.api.com"; 

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); 

    private static Retrofit.Builder builder = 
      new Retrofit.Builder() 
        .baseUrl(API_BASE_URL) 
        .addConverterFactory(GsonConverterFactory.create()); 

    public static <S> S createService(Class<S> serviceClass) { 
     Retrofit retrofit = builder.client(httpClient.build()).build(); 
     return retrofit.create(serviceClass); 
    } 
} 

然後我使用的服務生成類創建新的服務:

MyClient api = ServiceGenerator.createService(MyClient.class); 
     Call<MyItem> call = api.getMyItem(param1, param2, param3); 
     MyItem myItem= null; 
     try { 
      myItem= call.execute().body(); 
      Log.d("MyTag", myItem.getValue()); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

當我試圖運行此代碼我收到此錯誤:

android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147) at java.net.InetAddress.lookupHostByName(InetAddress.java:418) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) at java.net.InetAddress.getAllByName(InetAddress.java:215) at okhttp3.Dns$1.lookup(Dns.java:39) at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173) at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139) at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81) at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289) at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at okhttp3.RealCall.getResponse(RealCall.java:240) at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) at okhttp3.RealCall.execute(RealCall.java:57) at retrofit2.OkHttpCall.execute(OkHttpCall.java:177) at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87) at uz.cp.ox.data.MyRepository.getMyItem(MyRepository.java:31) at uz.cp.ox.presenters.MyPresenter.do(MyPresenter.java:30) at uz.cp.ox.activities.MyActivity.onClick(MyActivity.java:52) at android.view.View.performClick(View.java:4756) at android.view.View$PerformClick.run(View.java:19749) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5221) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

我認爲改造自動完成後臺線程的工作。或者我誤解了一些東西。這種情況出了什麼問題,以及如何解決?

+0

請檢查答案,並讓我知道如果您有任何顧慮 – Rahul

回答

29

I thought that Retrofit automatically does the job in the background thread.

它確實,如果你使用異步版本 - enqueue。您正在使用在調用線程上運行的同步版本。

這樣調用它來代替:

MyClient api = ServiceGenerator.createService(MyClient.class); 
Call<MyItem> call = api.getMyItem(param1, param2, param3); 
call.enqueue(new Callback<MyItem>() { 
    @Override 
    public void onResponse(Call<MyItem> call, Response<MyItem> response) { 
     MyItem myItem=response.body(); 
    } 

    @Override 
    public void onFailure(Call<MyItem> call, Throwable t) { 
     //Handle failure 
    } 
}); 

在onResponse(),使用response.body()得到您的回覆,如:
MyItem myItem=response.body();

編輯:固定onResponse()& onFailure處()的簽名並向onRespnose()添加了示例。

+4

如果我想同步調用服務該怎麼辦? – Iqbal

+0

請參閱OP的代碼: 'Call call = api.getMyItem(param1,param2,param3); (); body();' 使用'.execute()'而不是'.enqueue'。 – NightSkyDev

+2

好的,但當我們這樣做,我們得到'NetworkOnMainThreadException',我們不能做同步。打電話沒有異常? –

1

您正在呼籲主線程web服務,這就是爲什麼你長了這個錯誤「android.os.NetworkOnMainThreadException」。

您可以使用NightSkyDev回答的上述編碼來獲取您想要的數據。

2

在改造兩種類型的方法執行發生 - 入隊 - 工作後臺線程自動處理通過改造。 執行 - 在UI線程上工作,手動需要放入後臺線程或接受異步任務的幫助。

相關問題