Click here to Skip to main content
15,881,882 members
Articles / Mobile Apps / Android
Tip/Trick

Creating Progress Bar When Loading Two or More Async Tasks in Android

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
17 Dec 2018CPOL2 min read 9.2K   1   1
Tips for tracking progress on multiple async tasks in Android

Tips

In situations where we need to make multiple async tasks such as when an activity needs to make multiple recycles views (or fragments), we can reuse the same spinning progress bar widget until all of the async tasks have been completed. The async calls can be used for loading data over network or database or smoother long running tasks. Since the async tasks are happening in the background thread, attempting to start the spinner from the main thread and closing the spinner from background thread would result in exception of type "CalledFromWrongThreadException" which implies that only the original thread that created a view hierarchy can touch its views.

This can be accomplished by creating two variables, one to store number of requests made and another to store number of requests completed. The assumption is that the async task is an inner class of the calling class. The number of requests made is incremented before calling the async task. And number of requests completed is incremented onPostExecute function of async class. progress bar is initialized in the calling class. The progress bar's visibility is set to visible on start of the async class. The progress bar's visibility is hidden after onPost execute and only if the number of requests made is equal to the number of requests completed. Simple!

Below, I am outlining some major steps. I am hoping I would expand this article to add more details in future with full working code.

I defined two private variables to do count of async tasks in the activity that calls the async tasks. One counter tracks tasks have been requested and the other is for how many have been finished.

Java
private int AsyncTaskCount = 0;     //tracks number of requests completed
private int AsyncTaskRequested = 0; //tracks number of requests
private ProgressBar spinner;        //defined the progressBar

Initialize the progress bar on onCreate method for the calling class. 

Java
spinner = (ProgressBar)findViewById(R.id.progressbar);

Update the count of requested say prior to calling the asynctask:

Java
AsyncTaskRequested = 2;     //we are requesting two asynctasks
new NetworkQueryTask().execute(SmartStockConstant.QueryMarket);
new NetworkQueryTask().execute(SmartStockConstant.QueryStock);

On the asynctask class, update the AsyncTaskCount in the doInBackground and set the progress bar visible:

Java
class NetworkQueryTask extends AsyncTask<String, Void, ArrayList<Stock>> {
     private String query;

     @Override 
     protected ArrayList<Stock> doInBackground(String... params) { 
          AsyncTaskCount++; //track the executed 
          spinner.setVisibility(View.VISIBLE); //set the bar visible

Finally, onPostExecute, check if number of completed task equals number of requested and make the progressBar invisible:

Java
     @Override 
     protected void onPostExecute(ArrayList<Stock> searchResults) { 
          super.onPostExecute(searchResults); 
          //main logic here 

          if(AsyncTaskCount == AsyncTaskRequested) { 
               spinner.setVisibility(View.GONE); 
         } 
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
United States United States
Benktesh is a senior software engineer at Sony where he is a software developer/architect. His main focus when coding is quality, simplicity, and scalability and he is experienced in a broad range of subjects (software design, software development process, project management, testing, UI, multithreading, database, mobile development, and more).

Outside of professional work, there are always some side projects he is working on such as simulation modeling of financial, energy and emissions data and writing articles both technical and non-technical (see his blog at https://benktesh.blogspot.com/). While not coding, he is either reading books fiction and/or non-fiction, watching tv shows, trading stocks, and discussing climate change, global warming, emission trading, and traveling to meet people, place, and culture.

Comments and Discussions

 
PraiseNice idea Pin
David Crow20-Dec-18 8:45
David Crow20-Dec-18 8:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.