Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask: where does the return value of doInBackground() go?

When calling AsyncTask<Integer,Integer,Boolean>, where is the return value of:

protected Boolean doInBackground(Integer... params)?

Usually we start AsyncTask with new AsyncTaskClassName().execute(param1,param2......); but it doesn't appear to return a value.

Where can the return value of doInBackground() be found?

like image 681
Dhruv Mevada Avatar asked Dec 20 '10 11:12

Dhruv Mevada


People also ask

How do I get return value from doInBackground?

You can retreive the return value of protected Boolean doInBackground() by calling the get() method of AsyncTask class : AsyncTaskClassName task = new AsyncTaskClassName(); bool result = task.

When AsyncTask is executed it goes through what steps?

An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.

What is the use of the AsyncTask class?

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.


1 Answers

The value is then available in onPostExecute which you may want to override in order to work with the result.

Here is example code snippet from Google's docs:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {       protected Long doInBackground(URL... urls) {           int count = urls.length;           long totalSize = 0;           for (int i = 0; i < count; i++) {               totalSize += Downloader.downloadFile(urls[i]);               publishProgress((int) ((i / (float) count) * 100));           }           return totalSize;       }        protected void onProgressUpdate(Integer... progress) {           setProgressPercent(progress[0]);       }        protected void onPostExecute(Long result) {           showDialog("Downloaded " + result + " bytes");       }  } 
like image 112
Konstantin Burov Avatar answered Oct 14 '22 10:10

Konstantin Burov