How To Handle Network On Main Thread Error In Android

NetworkOnMainThreadException is a pretty popular exception among those new to android development. This exception is mainly thrown whenever an application attempts to make a networking operation (like an API call or Http request) on its main thread. The other aspect of this exception is that it is only thrown by applications targeting the Honeycomb SDK or higher. That means that anything below that will allow you to make network operations or requests in your main thread without causing the popular “YourAppName has stopped working …force close or wait” message. In this post, I will show you how to solve this problem once and for all.

network on main thread solution

Network On Main Thread Exception – Temporary Workaround

Assuming you have ran into this problem and all you really want to do is test something quickly before eventually writing your code to avoid making network operations on main thread, there is a simple workaround that you can use. With just a few lines of code, you can get the same results. By adding these few lines of code to your Activity or wherever you want to make a network operation, you enable StrictMode.

Again, this is a dirty way to make network operations and I will be showing you the right way to do in the next section of this post. Now, once you have that method, before you make any network calls, just do the following:

Just like learning to code, there is the easy and bad way to do and then there is the right way. The point is that you don’t want to give your app’s users a hellish experience. Think of it this way, would you like an app that keeps crashing? The answer is obviously an astounding NO. Let us look at the right way to solve network on main thread error in android, shall we?

Network On Main Thread Exception – The Right Way To Do It

Android is awesome. Allow me to say that here. The reason why you are not supposed to perform network operations on the main thread is because there is a better way to do so. Android provides a class called AsyncTask.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

Use cases

  • Allow users to authorize your app to access their social network accounts like Facebook, Twitter, Google+ using OAuth.
  • Download some resources in the background without freezing the UI. Then updating the UI simultaneously.
  • Really, doing anything that requires networking.

Having said that, let us take a look at how you can use this AsyncTask in real life.

As you can see, there are several methods that you can Override in your AsyncTask. You have to override the doInBackground() method. There is also another method called onPreExecute() which you can use to prepare whatever you need before doing the real stuff in the background. In onPostExecute method, you can update the UI with the newly downloaded resources like update a list view or a user profile after they have authorized your app.

How To Execute an AsyncTask

In the method that you want to make network operations – load normally on your main thread, do;

Something To Notice

  • The first argument will be the type that doInBackground will expect – in this case URL.
  • The second argument will be the same type as that expected by onProgressUpdate method.
  • The third and last argument will be the same type passed onto onPostExecute method.
  • Summary

    In general, you should avoid making network operations on the UI thread because it will slow down your app and eventually crash it. Instead, use an AsyncTask which runs in the background. That is the right way to go if you are a good android developer.

    To learn more about AsyncTasks, please click here.

    That is it for today because I initially planned not to make this post too long. If you liked it and found it helpful, please consider sharing it online using the buttons below. If you have any questions regarding async tasks, please do not hesitate to ask me through the comments or the contact page.

    Thank you for stopping by and stay tuned for more awesome stuff by subscribing to my blog.

Written By Elisha Chirchir

Elisha Chirchir is a software developer. He is also the founder of Simple Developer and co-founder of Instinctive Software Solutions. On any given day, he works on both Android and Web Development. During his 'free time', he offers training to those interested in learning how to code in php, java, python, javaScript etc. You can easily find him on StackOverflow Android chatroom or on Twitter @Eenvincible

2 Comments on “How To Handle Network On Main Thread Error In Android

  1. Larry Zingrich Reply

    June 1, 2015 at 6:53

    That error has caused my phone’s Network Interface to be lo and IP to be ::1%1 (lo loopback).What is this? It controls my connections.

  2. Jorgesys Reply

    February 2, 2018 at 5:04

    AsyncTask extends AsyncTask
    must be:
    AsyncTask extends AsyncTask

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.