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.

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

How to get started with Android development – Basic structure

andro02In a previous article, I wrote about how you can launch your first Android application from the samples provided with Android Studio. Now that you’ve had a chance to poke around a few samples, I’m going to tell you a bit about the basic structure of an Android application.

A good place to start understanding an application is the manifest. The AndroidManifest.xml file links all the parts of an Android application together, including:

  • The activities contained in your application,
  • The theme you use,
  • The name of the application and its icon on the main screen,
  • The permission the application must request to run.

Activities and the java folder

The Java code of your application lives in the java folder. The first class you’ll create is a Activity class, which is the main building block of all Android applications. An activity is a full screen window in which all your code will run. Each activity has it own life cycle which starts when it’s first launched and last until it is finally destroyed.

The user navigates between different activities in your application: the back button of the device closes the current activity by default and goes back to the previous one. If the user closes the first activity of your application, he’ll go back to the application that was previously open, if any. You can also launch other applications (with their own activities) using intents. You can use this to request an application that can send an email or play music, and the installed applications that can manage this will be displayed to the user.

The activity life cycle can be affected by events outside your control: for example, if a phone call comes in, your current activity (so your application) will be paused. Each activity has a layout associated with it that describes how controls that are displayed, and the activities are declared in the AndroidManifest.xml file.

Unfortunately, the fact that the activity is bound pretty strongly to the navigation AND to the user interface/layout makes it hard to separate the business logic and the display logic properly. You can create a usable Android application with only a .java file with an Activity class, but eventually you’ll want to move on to a better architecture. There are some patterns out there that can help you do this, but for your first application you should stick with this and avoid introducing additional complexity.

Resources

Resources are everything that your application needs that is not Java code, such as layouts, strings, images and other constants. The Android API uses XML for most resources. The res folder contains all the resources of your application, such as:

  • XML layouts for each activity and component in the layout folder, styles in the values\styles.xml and images in the drawable folders. Layouts in Android are inspired by HTML/CSS, so if you’ve ever done some web development you’ll feel right at home pretty soon.
  • All the strings used in your application in values\strings.xml. You can hardcode them in the layouts, but if you ever need to translate your application you’ll be glad you put them all in one place to get started with.
  • Menus for your application are defined in the menu folder.

See the other articles in the series here