Async Task with Running UI thread In Background |Android Studio
Introduction
Android AsyncTask is an abstract class which
The basic methods used in an android AsyncTask class are:
- doInBackground(
) : This method contains the code which needs to be executed inbackground . In thismethod 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 fromdoInBackground method, which is published viapublishProgress 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
<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
- Put your Cursor on AsyncTask<> class and click CTRL+O to implement more methods of the abstract class.
- Image loaded from
picasso will be cached so when you run your app again image will be already displayed as it was cached. - 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.