Skip to main content
+234 803-795-2621
Brace yourself, loaders are coming
Thu, 08/17/2017 - 10:02

Loads of Stuff

While using my android phone in the past, I have been skeptical about using some features initially there to make me more comfortable. One of these features was the Auto Rotation feature. While this feature is on, my smartphone usage is the bomb because by rotating the screen, I can easily view a picture from a different dimension, watch YouTube videos in full screen, and maximize the UI of various mobile applications.

So why do I toggle the Auto rotation off? Apart from the convenience I get when I press my phone while lying down, some Apps just seemed to load forever (or reload when the screen rotates) and the phone becomes slower. A few weeks into my Android course, I came to the conclusion that those were just poorly programmed mobile apps.

AsyncTask

Without being too technical, let us discuss AsyncTask. AsyncTask is a class that allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask is majorly used for performing operations that last only a few seconds. Operations in this category could include connecting to a website and uploading or downloading content. An asynchronous task has four main steps: onPreExecute, doInBackground, onProgressUpdate and onPostExecute. When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), is invoked on the UI thread before the task is executed. This step is normally used to setup the task.
  2. doInBackground(Params...), is invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. (Params… is one of the three generic types of the AsyncTask class). The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress (Progress is the second generic type associated with the AsyncTask).
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), is invoked on the UI thread after the background computation finishes (Result is the third generic type of the AsyncTask class). The result of the background computation is passed to this step as a parameter.

 

Consider an app that is opened, the AsyncTask class with its method are called, say, to download information from a website. Whenever the phone is rotated, a new activity gets created from the scratch, so does a new AsyncTask method. This means that the activity that was being loaded prior to that will be kept in the memory till the activity finally ends (Rotating the phone is akin to sending data requests). This means that the activity starts loading again when the phone is rotated and the updates from the initial loading action are no longer useful. This is a major memory leak (I‘ll write more on that soon). Imagine a case where the phone is rotated multiple times, the memory used up will be massive (Little wonder!).

Why use Loaders?

Loaders play a major role in the efficiency and sustainability of android mobile applications. When using loaders, no matter how many times data is requested from a loader, the loader fetches data only once. When an activity shuts down, the loaders will quit as the data will not be used. Loaders also monitor the source of their data and deliver new results when contents change. Loaders, alongside the LoadManager, provide an abstract class called AsyncTaskLoader to perform the background tasks more efficiently. A simple implementation of the AsyncTaskLoader is given below:

 

AsyncTaskLoader Implementation

public class EarthquakeLoader extends AsyncTaskLoader<List<Quake>> {
    private String murl;
    /** Tag for log messages */
    private static final String LOG_TAG = EarthquakeLoader.class.getName();

    public EarthquakeLoader (Context context, String url) {
        super(context);
        murl = url;
    }
//Start loading method
    @Override
    protected void onStartLoading(){
        forceLoad();
    }
//Load in background method
    @Override
    public List<Quake> loadInBackground() {
        // Don't perform the request if there are no URLs, or the first URL is null.
        if (murl == null) {
            return null;
        }

        List<Quake> earthquakes = Query.fetchEarthquakeData(murl);
        return earthquakes;
    }
}

Generally, Loaders prevent apps from crashing due to multiple screen orientation changes. Loaders also helps the programmer to exercise better control mechanism over the app by managing the lifecycle of the activities.

Finally, while an AsyncTask lives as long as the Task exists even if the activity dies, the loaders are tied to the Activity Lifecycle.

I am a Software Developer in KodeHauz, a technology enthusiast and a knowledge tank.

Are you ready to take your business global?

Request a quote
click here.