Search code examples
androidandroid-asynctask

Returning data from AsyncTask without blocking UI


I have a conceptual problem related to AsyncTask class. We use AsyncTask so that the main UI is not blocked. But suppose, I want to retrieve some data from the device's memory, and I use AsyncTask class for this. The relevant line of the code will be as follows (assuming the data type returned is String):

  //code
    String data = new ExtendedAsyncTask().execute(param1, param2).get();
  //use this returned value.

Won't the above line block the UI, defeating the purpose of using the AsyncTask ? If yes, then how do I get the relevant data without blocking UI ? I would like to add that the next line of code will need this data to perform some task, and hence depends on the returned value.

Thanks


Solution

  • get() method will block the UI thread. To get the relavent data you need to return the value from doInBackground and capture the value in onPostExecute parameter.

    Value returned by doInBackground is captured by onPostExecute method

    Example:

    public class BackgroundTask extends AsyncTask<String, Integer, String >{
           private ProgressDialog mProgressDialog;
           int progress;
           public BackgroundTask() {
               mProgressDialog = new ProgressDialog(context);
                 mProgressDialog.setMax(100);
                 mProgressDialog.setProgress(0);
        }
    
           @Override
        protected void onPreExecute() {
               mProgressDialog =ProgressDialog.show(context, "", "Loading...",true,false);
            super.onPreExecute();
        }
         @Override
         protected void onProgressUpdate(Integer... values) {
         setProgress(values[0]);
      }
    
        @Override
        protected String doInBackground(String... params) {
                String data=getDatafromMemoryCard();    
    
            return data;  // return data you want to use here
        }
        @Override
        protected void onPostExecute(String  result) {  // result is data returned by doInBackground
            Toast.makeText(context, result, Toast.LENGTH_LONG).show();
            mProgressDialog.dismiss();
            super.onPostExecute(result);
        }
       }
    

    If you are using asynctask in separate class, then use AsyncTask with callback interface like this

    Here is the answer I have provided earlier about the same AsyncTask with Callback