Fixing the NetworkOnMainThread exception in your Android app with AsyncTask

As soon as you start doing long-running operations such as network calls or anything else that can take more than a few seconds in your Android application, you’ll come across one of the following problems:

  • The [Application] not responding (ANR) popup is shown while you run your application, and the The application may be doing too much work on its main thread. warning is shown in your Logcat traces.
  • The NetworkOnMainThreadException exception is launched as soon as you call anything over the network like an API, regardless of the duration of the call.

Why does the Android SDK complains when one of those things happens? Why does code that seems to be correct doesn’t work? Well, if your application stays frozen, your users could think it crashed. A few seconds is an eternity when you don’t have any feedback about what’s going on, and users are probably going to keep pressing buttons as a response, or close your application and never return. So, to prevent this, the Android SDK enforces minimum standards for responsiveness and display errors if those standards are not respected.

To understand why the application freezes, we must take a look at the architecture of the application. By default, your Android application has only one thread, called the main thread. All you code execute on this single thread, and a thread can only do one thing at a time.

So, if you call the network and there is a delay, everything stops while the application waits for an answer, freezing your UI completely. You won’t even be able to display a progress bar because nothing else can run. The timeline looks like:

Fortunately, you can create new threads, which allow you to do more than one thing at once:

For one-time operations that only takes a few seconds, the easiest way to manage this is to use the AsyncTask class available in the Android SDK. It will create a new thread for you that will do a specific task, and then notify you when that task is over so you can update your UI.

Here is an example of an AsycTask that calls the GitHub API to calculate the number of repository that contains the “Android” string. While the query is running, a progress bar is shown in the UI.

private class GithubAndroidRepositoryQueryTask extends AsyncTask<String, Integer, String> {

@Override
protected void onPreExecute() {
   super.onPreExecute();
   // Prepare the UI in the main UI thread before executing the task.
   mGitRepositoryProgressBar.setVisibility(View.VISIBLE);
}

@Override
protected String doInBackground(String... params) {
   // Do the operation on a new thread and returns the result. It calls the GitHub API to 
   // calculate the number of repository that contains the Android string
   return getAndroidRepositoryCountFromGitHub();
}

@Override
protected void onProgressUpdate(Integer... progress) {
   // Could be used to update the main UI thread with the progress of the background
   // operation.
}

@Override
protected void onPostExecute(String result) {
   // Receive the result of the operation done in the new thread in the main UI thread and
   // use it to update the UI.
   super.onPostExecute(result);
   mGitRepositoryProgressBar.setVisibility(View.INVISIBLE);
   mGitRepositoryTextView.setText(result);
}
}

And here is how you execute that task. In that case, it’s launched onCreate event of the Activity so the response is visible immediately in the layout, but it could be launched from anywhere else:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   mGitRepositoryTextView = (TextView) this.findViewById(R.id.github_repositories_tv);
   mGitRepositoryProgressBar = (ProgressBar) this.findViewById(R.id.github_repositories_pb);

   // Fires off an AsyncTask to get the number of Android repositories on GitHub and displays
   // it in the application.
   new GithubAndroidRepositoryQueryTask().execute();
}

When you’re working with threads of any kinds, remember that updating the UI should only be done on the main thread. The Android SDK doesn’t support updating the UI from other threads, so you’ll likely have random crashes and weird behavior if you attempt it.

Also, as a caveat, Google doesn’t recommend relying on showing a progress bar exclusively for long-running operations. They believe that users should be able to keep working in the application and that you should manage what’s going on in the backend.

If you have a simple application that has only a few simple cases it may work, but if you have complex interactions between your data you can sink a lot of time trying to make everything work nicely together and handling what happens if an operation fails.

Still, you can start with a simple AsyncTask and optimize as you go along. In most cases, it’s going to be a good starting point, but as soon you need to execute many tasks at once it won’t be enough. When you’re ready to go further with this, you should take a look at libraries such as RxJava to help you manage your tasks.

Want to learn new programming skills quickly?

Subscribe to my newsletter to receive my 5 Hacks to Learn New Skills email course directly in your inbox.

You’ll also receive updates about what's going on with the blog.

How to get started with Android development – Layout Managers

At the end of my last article, I left you hanging after describing activities, without telling you how to build a UI, so here we go. In the Android SDK, layouts are separate from the Java code that defines how an activity behaves. Using this separation of concern, it’s easier to modify the layout without having to worry about the code.

Android layouts are in XML, and are located in the res\layout folder. You can have multiple versions of a layout for various orientations, screen size or culture and the Android SDK will choose the right one according to the device. We won’t worry about this right now; for simple layouts one version is enough.

In this article, I’m going to show you how to use a layout manager to position a widget, called a View in the Android SDK, using XML and Java. Next time, I’ll complete this explanation with more details about views themselves, and how they can be controlled in the layout or programmatically.

There is also a designer tool in Android Studio to help build your layouts. I’ll stick to the code for now since I believe it’s best to understand how things are built manually first, and then you’ll know enough to be able to explore it on your own.

Your First Layout

Here is a simple layout with two TextView views, each showing a text string, inside a LinearLayout layout manager in the res\layout\activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="My first textview"/>
    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:text="My second textview"/>
</LinearLayout>

Each layout has a least one view as a root, but it’s usually a layout manager such as the LinearLayout, RelativeLayout or ConstraintLayout since those views are built to position other views. I used the linear layout in this example since it’s simple to understand: if the property android:orientation is set to vertical, all the views will be aligned one over the other, and if set to horizontal they will be side by side.

To use your layout with your activity, you must set the layout in the onCreate() event of the activity using the setContentView() method :

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
} 

Views and Layout Managers Properties

All views, including layout managers, have proprieties that can be added to their XML declaration to control their size and padding. For example, you can specify an android:layout_height and android:layout_width in dp (density-independent pixels) like the layout above, or use the wrap_content and match_parent values:

  • wrap_content: The size (width or height) of the view will be the size required to display its content. For example, if you have a very long view showing text, you’ll use wrap_content as the height so it doesn’t get truncated at the bottom.
  • match_parent: The size (width or height) of the view will be the same as the size of its parent layout element. This used to be called fill_parent in API level 7 and less, so you’ll still see that name from time to time.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
              android:layout_width="match_parent" 
              android:layout_height="match_parent" 
              android:orientation="vertical">
    <TextView android:layout_width="match_parent" 
              android:layout_height="wrap_content" 
              android:text="My first textview"/>
    <TextView android:layout_width="match_parent" 
              android:layout_height="wrap_content" 
              android:text="My second textview"/>
</LinearLayout>

Each layout manager also has properties to control the positioning of the views they contain, such as the android:orientation for the LinearLayout described previously.

Layout managers can be nested to create complex layouts: for example, you can add a vertical linear layout inside a horizontal linear layout or a grid layout. Still, to make rendering more efficient, you should be careful to avoid nesting too many layouts.

So next time, we’ll take a look at how to use complex views that requires an interaction from the user, and how control those views from your Java code.

See the other articles in the series here

Are You Hard to Convince?

When discussing a new technology, I’m rarely the first one to jump on the bandwagon. In fact, I’m usually the killjoy that ends up arguing against using a new library or a new language feature when the enthusiasm is high and everybody is eager to get started.

It’s not that I want to stay comfortable and never move forward. Rather, I need to be convinced that something is worth it instead of moving for the sake of it. New features and libraries can add complexity to something that’s already complex. That makes it harder for new people to join in (including you if you didn’t touch it for the last 6 months).

I’m all for new ideas that makes software easier to understand and that allows me to do my job better. Still, the argument about new technology is too focused on the shiny new technology itself, and not the problem it solves. A great idea is not enough; it has to work well in the real world.

To illustrate this, I choose a few templating engines at random on npm (not judging their quality; maybe they’re all great). Here is the kind of descriptions that will greet you:

Why should I choose one over the other, or use it to replace an existing tool?  A description like fast and powerful is not very helpful. It’s good to have, but who would pick a underpowered, slow engine?

Of course, if I’m looking specifically for an HTML template engines I can narrow it down a bit, but if I don’t have a strong preference one way or the other, what should I choose? There were surely a few problems or use cases that led to writing those engines instead of using an existing one, but I don’t have any way of knowing from looking at this.

At this point, I’m asking myself if the library will still exist in 5 years (without forcing me to rewrite everything every year) and if it’s well documented so I can get up to speed quickly, not if it implements a cool pattern in particular.

If I had to choose something for a project from that list, I would probably pick the ones that have the most promising documentation and a large following, and try them out for myself. Granted, it could still blow up later in production or when trying to implement a feature in particular since I’m only coding a prototype, but it’s better than nothing.

But after doing all this work, why would I switch to something new a few years down the line if the one I choose first still works well? I have to be really convinced that it can solve my problem better, and that is worth the cost of switching in improved productivity and ease of use. With the speed that the technology is moving I must be sure it’s worth it. I can’t afford to waste my time migrating to something that will make things worse.