Retrofit - android.os.NetworkOnMainThreadException

青春壹個敷衍的年華 提交于 2019-12-04 00:16:47

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

It does if you use the asynchronous version - enqueue. You're using the synchronous version, which runs on the calling thread.

Call it this way instead:

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
    }
});

In onResponse(), use response.body() to get your response, such as:
MyItem myItem=response.body();

Edit: Fixed onResponse() & onFailure() signatures and added example to onRespnose().

Sai Soe Harn

You are calling webservice on main thread, that's why u got this error 'android.os.NetworkOnMainThreadException'.

You can use the above coding answered by NightSkyDev to get the data what u want.

In Retrofit Two Types of Method execution takes place- Enqueue - Works on background thread automatically handle by retrofit. Execute - Works on UI thread manually required to put in either background thread or take help of async task.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!