I have an app that sends a http request to a server and receives a JSON for processing. I test it on both a physical device and Genymotion.

The app runs fine on the physical device but on Genymotion throws NetworkOnMainThreadException.

I tracked the exception and this is the part with the issue:

..
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

// Exception on this line:
HttpResponse httpResponse = httpClient.execute(httpPost);
//
HttpEntity httpEntity = httpResponse.getEntity();
...

It seems that the Genymotion can't connect to server to execute the request. But its browser loads the sites just fine.

So, anyone knows what's going wrong here?

有帮助吗?

解决方案

I found what the problem was:

As explained in this answer, since API 11, the NetworkOnMainThreadException is thrown to inform using long-running tasks (like http communications) in the main thread.

By using AsyncTask the problem was resolved and everything worked as it should.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top