android-logo

AsyncTask in Android


The AsyncTask (Asynchronous Task) feature in Android makes it possible to run a task in the background and synchronize with our main thread again. At least one method in this class will be overridden i.e. doInBackground(Params), and most commonly onPostExecute(Result).


AysncTask workflow

volley-library

We will learn about how to run networking operations on a different thread and how to use Androids networking client to grab data from a network. Finally, we will learn how to parse the results in order to extract our specific value from an information.

For our example, we are going to pull json from a movie API and set the result into textview.


Movie JSON link

https://www.androidaura.com/json-files/avengers-movie.json


Postman tool to check our API calls

volley-library

Listed below are the contents of the modified main activity file.

MainActivity.java


package com.example.androidaura;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tv1);

        new GetMovie().execute();
    }

    private class GetMovie extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

    @Override
    protected Void doInBackground(Void... arg0) {
          String apiUrl = "https://www.androidaura.com/json-files/avengers-movie.json";

          try {
              URL url = new URL(apiUrl);
              HttpURLConnection  urlConnection = (HttpURLConnection) url.openConnection();
              InputStream stream = new BufferedInputStream(urlConnection.getInputStream());

              BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
              StringBuilder builder = new StringBuilder();

              String inputString;
              while ((inputString = bufferedReader.readLine()) != null) {
                  builder.append(inputString);
              }

              JSONObject object = new JSONObject(builder.toString());
              String name = object.getString("movieName");
              textView.setText(name);
              urlConnection.disconnect();

          } catch (IOException | JSONException e) {
              e.printStackTrace();
          }
          
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
    }
  }
}

Add below code in your XML

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="26sp"
        android:gravity="center"
        android:text="asadad"
        android:ems="10" />

</androidx.appcompat.widget.LinearLayoutCompat>

Give internet permission

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />

Output
rating-bar-1

previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.