Retrofit or Asynctask?

Why use Background Task?

By default, application code runs in the main thread. Every statement is therefore executed in sequence. If you perform a long lasting operation, the application blocks until the corresponding operation has finished. To provide a good user experience all potentially slow running operations in an Android application should run asynchronously. This can be archived via concurrency constructs of the Java language or of the Android framework. Potentially slow operations are for example network, file and database access and complex calculations.

Android modifies the user interface and handles input events from one single thread, called the main thread. Android collects all events in this thread in a queue and processes this queue with an instance of the Looperclass.

Android supports the usage of the Thread class to perform asynchronous processing. Android also supplies the java.util.concurrent package to perform something in the background. For example, by using the ThreadPools and Executor classes. If you need to update the user interface from a new Thread, you need to synchronize with the main thread. Because of this restrictions, Android developer typically use Android specific code constructs. Android provides additional constructs to handle concurrently in comparison with standard Java. You can use the android.os.Handler class or the AsyncTasks classes. More sophisticated approaches are based on the Loader class, retained fragments and services.

Using AsyncTask

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams, ProgressValue, ResultValue>.

An AsyncTask is started via the execute() method. This execute() method calls the doInBackground()and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input. ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method. This parameter is passed to onPostExecute() as a parameter.

The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.

The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            // we use the OkHttp library from
            OkHttpClient client = new OkHttpClient();
            Request request =
                    new Request.Builder()
                 Response response = client.newCall(request).execute();
                 if (response.isSuccessful()) {
                     return response.body().string();
            return "Download failed";

        protected void onPostExecute(String result) {

    public void onClick(View view) {
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "" });


Run your application and press the button. The defined webpage is read in the background. Once this process is done your TextView is updated.

What is Retrofit?

Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit you configure which converter is used for the data serialization. Typically for JSON you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.

To work with Retrofit you need basically three classes.

  • Model class which is used to map the JSON data to
  • Interfaces which defines the possible HTTP operations
  • Retrofit.Builder class – Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.

Every method of an interface represents one possible API call. It must have a HTTP annotation (GETPOST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.

Call<List<User>> getUsers()

You can use replacement blocks and query parameters to adjust the URL. A replacement block is added to the relative URL with {}. With the help of the @Path annotation on the method parameter, the value of that parameter is bound to the specific replacement block.

Call<List<Commit>> getCommitsByName(@Path("name") String name)

Query parameters are added with the @Query annotation on a method parameter. They are automatically added at the end of the URL.

Call<User> getUserById(@Query("id") Integer id)

The @Body annotation on a method parameter tells Retrofit to use the object as the request body for the call.

Call<User> postUser(@Body User user)

Leave a Reply

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