I have an asynctask that is in its own activity. I pass it a string value and it connects to my web service and downloads Json data based on the name I pass in, returning the Json resultset. Works great.
I’d like to add a progress spinner to the asynctask, but I’m stymied as to how to do it. I’ve perused this and many other blogs, and come close but have not yet found the solution. It seems I either need to have the asynctask in with an Activity class to get the context or I have to pass in the context as a parameter — but I need the input parameter to be String. I’ve read about the possibility of building an Object that could hold the String and a Context parameter, but I’m very new to Java and don’t know how to build something like that nor have I found a good explanation of how to do so. So often an explanation gets right up to what I need and then says, “… and then you do X and that’s it,” when X is what I need to know.
All I want is just a spinner thingie to whirl while the download happens. No text, no dialog, just a spinner.
Add a ProgressBar(this is what it’s actually called, Spinners are like drop down menus in Android) to the layout of the Activity where you’re initializing your AsyncTask.
Then make two functions
startProgress()andstopProgress(), which start and stop the progress bar.Give your AsyncTask a reference to the Activity, either by sending it during initialization or execution, or making a function in your asyncTask
setActivity(MyActivity activity)and call it between your AsyncTask initialization and execution.Override the
onPreExecute()of your AsyncTask to callactivity.startProgress()andonPostExecute()to callactivity.stopProgress().EDIT: You can also try passing a reference to the ProgressBar in the constructor of your AsyncTask. Get the reference to the ProgressBar in the
onCreate()method of your activity, then add it in the AsyncTask constructor. In theonPreExecute()andonPostExecute()methods of the AsyncTask, start and stop the progress bars accordingly.