How do I return a boolean from AsyncTask in Android?


Introduction

Async Task is a class in android which is being used to perform some background long running tasks such as loading the images from the internet in background. If the image is huge in size then we can load that image from the internet as a background task using AsyncTask in Android. In this article we will take a look at How to return a boolean from an Async Task in Android.

Implementation

We will be creating a simple application in which we will be displaying a text view for heading of the application. Then we are creating one more text view in which we will be displaying the task is running or stopped. After that we are creating a button which is used to start the task.

Step 1: Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2: Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. Inthe left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for heading -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Returning Boolean from Async Task in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a message -->
   <TextView
       android:id="@+id/idTVMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Message"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />

   <!-- on below line creating a button to start out task -->
   <Button
       android:id="@+id/idBtnStartAsyncTask"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVMsg"
       android:layout_margin="20dp"
       android:text="Start Asnync Task"
       android:textAllCaps="false"
       android:textColor="@color/white" />
</RelativeLayout>

Explanation: In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating one more text view in which we will be displaying the current task status which we are performing within the application. After that we are creating a button which we will be using to start the task and the task will run for upto 5 seconds and then it will terminate.

Step 3: Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {

   // creating variables for button and text view.
   private TextView msgTV;
   private Button asyncTaskBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       //initializing variable for text view and button on below line.
       msgTV = findViewById(R.id.idTVMsg);
       asyncTaskBtn = findViewById(R.id.idBtnStartAsyncTask);

       //  adding on click listner for button on below line.
       asyncTaskBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
        // on below line calling our async task manage class
               AsyncTaskManage asyncTaskManage = new AsyncTaskManage();
               // on below line calling execute method to execute it.
               asyncTaskManage.execute("");
           }
       });
   }
   // on below line creating async task manage class.
   private class AsyncTaskManage extends AsyncTask {

       // on below line creating do in background method.
       @Override
       protected Boolean doInBackground(String... strings) {
           // on below line running try and catch block.
           try {
               // on below line sleeping the app by calling sleep method.
               Thread.sleep(3000);
               // on below line returning as false.
               return false;
               // on below line doing exception handling.
           } catch (Exception e) {
               e.printStackTrace();
           }
           // on below line returning as true.
           return true;
       }
       // on below line creating a post execute method.
       @Override
       protected void onPostExecute(Boolean aBoolean) {
           super.onPostExecute(aBoolean);
           // on below line checking if boolean is true or false.
           if (aBoolean) {
               // on below line setting text message as task running.
               msgTV.setText("Task is running..");
           } else {
               // on below line setting message as task stopped.
               msgTV.setText("Task is stopped..");
           }
       }
   }
}

Explanation: In the above code firstly we are creating variables for our text view and button. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the text view and button variable with the id which we have given in our activity_main.xml file. After that we are adding an on click listener for our button. Inside the click listener method we are calling the async task and calling an execute method to execute it. After that we are creating a class named AsyncTaskManage and extending it with AsyncTask. Inside this class we are creating a do in the background method. Inside this method we are sleeping out task to 5 seconds and in that case we are returning the boolean value as false and after that for the default case we are returning the value as true. Now we are creating one more method as on post execute. Inside this method we are checking the boolean value which we have returned to do in the background method. If the boolean is true we are specifying the message in text view as task is running, if the boolean value is false then we are specifying the message in text view as task is stopped.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above article we have taken a look on How to return the boolean value from a Async Task in Android.

Updated on: 08-May-2023

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements