Advertisements

Async Task with Running UI thread In Background |Android Studio

Introduction

Android AsyncTask is an abstract class which perform heavy tasks in the background and keep the UI thread light thus making the application more responsive and App does not crash or get slow!

Android application runs on a single thread(UI thread/ Main Thread) when launched. Due to this single thread model tasks that take longer time to fetch the response can make the application non-responsive. To avoid this we use android AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back to the UI thread.

The basic methods used in an android AsyncTask class are:

  • doInBackground() : This method contains the code which needs to be executed in background. In this method we can send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements.
  • onPreExecute() : This method contains the code which is executed before the background processing starts
  • onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method
  • onProgressUpdate() : This method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update the UI thread

Let’s Code:

We are going to create a project in which we will call a Image from URL through Picasso! Watch my full tutorial on how to use Picasso and then we are going to show a list view containing integer number and has Power 3 like(1,8,27,64…). First Create an Android Studio Project “AsyncTask” and write in activity_main.xml

    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:text="Running Ui thread In background"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"
         />

    <ImageView
        android:id="@+id/imgview"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
<ListView
    android:id="@+id/listview"
    android:layout_below="@id/imgview"
    android:layout_marginTop="20dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></ListView>
</RelativeLayout>

Now go to your gradle(app):

dependencies {
    implementation 'com.squareup.picasso:picasso:2.5.2' 
}

Now in your manifest file give Internet permission for loading images from URL.

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

Go to your MainActivity.java

package com.example.asynctask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    ProgressDialog progressDialog;
    ArrayAdapter adapter;
    ArrayList mylist;
    ImageView imageview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.listview);
        imageview = findViewById(R.id.imgview);
        LoadImage loadImage = new LoadImage();
        loadImage.execute();
    }


    public class LoadImage extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Calculating Data....");
            progressDialog.setCancelable(false);
            progressDialog.show();

        }

        @Override
        protected Object doInBackground(Object[] objects) {
            mylist = new ArrayList();

// Running Code on Ui thread
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
//Loading Image From Picasso
                    Picasso
                            .with(MainActivity.this)
                            .load("https://life-news.blog/wp-content/uploads/2018/12/51xHIs1-zXL.jpg")
                            .resize(270, 250)
                            .into(imageview);

                }
            });
            try {
//filling List
                int i;
                int j;
                for (i = 1; i <= 20; i++) {
                    j = i * i * i;
                    mylist.add(j);
                }
//Optional if you want results to be published after some time
                int time = 5 * 1000;
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            progressDialog.hide();
// filling adapter for list view
            adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_expandable_list_item_1, mylist);
            listView.setAdapter(adapter);
        }

    }
}

Tips

  1. Put your Cursor on AsyncTask<> class and click CTRL+O to implement more methods of the abstract class.
  2. Image loaded from picasso will be cached so when you run your app again image will be already displayed as it was cached.
  3. Don’t forget to execute() your Asynnct task class in your methods or other classes.

Comment if you still have Some Issues or Rate and share my Content. Also you can subscribe to my posts for regular updates.

How useful was this post?

Do not forget to rate! this helps us to Improve.

Average rating / 5. Vote count:

Read More Like This..

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Advertisements

Safiya Akhtar

Safiya Akhtar is Android Application Developer in India. She is currently working as a public consultant for career and education too, besides blogging and freelancing. She believes that it is never too late or too early to start what you have always dreamed of.

Your Views And Question are Welcome Here!

Advertisements