Hi folks,
Like me, if you are new to android platform and working with network requests such as using HttpRequest, HttpGet, or HttpPost etc. YOU may come across a “NetworkOnMainThread” exception or your application stopped responding. This really annoys in a way that your code complies nicely and smells like *it should work* but on runtime it throws an exception which result in application termination.
The other day I was working with RESTful services and was developing a sample code to send simple HttpPut request to my services and got this error.
Solution:
Most likely the root cause will be either you are calling some network activity on your main thread and it has restricted thread policy and/or your app does not have enough permission. It can be solved by taking following steps:
- In AndroidManifest, make sure your application has permission to access network/internet.
- Use AsyncTask to enable network request to run asynchronously on another thread. Following is the code snippet that demonstrates use of HttpPut request using AsyncTask
Disclaimer:The code below is not optimized to be used in production environment, it’s just a sample to give idea about the solution. All views expressed are mine only
This would solve the problem!
For further reading, I would suggest to go through an article on performance “Android Threads, Handlers, and AsyncTask – Tutorial”
0 Comments