Android NetworkOnMainThread Exception

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.


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:

  1. In AndroidManifest, make sure your application has permission to access network/internet.

  2. 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

Awarded Microsoft MVP 2012

I am glad and EXCITED to share that I have been awarded 4th time “Microsoft Most Valuable Professional (MVP)” by Microsoft Corporation, USA. This is really a great achievement for me in terms of consistency for my contribution in online and offline technical communities. I would like to thank every single one of you who supported me in my professional and personal life that made me achieve something outstanding.

If you want to know about MVP Award and how become one, you can read one of my blog post on “How to become Microsoft Most Valuable Professional

Following is the content copied from announcement email:

Dear Adil Mughal,

Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual C# technical communities during the past year.

Thanks for your support!