Reputation: 11
I'm trying to show a progress bar only while a task is running, this is my code
public void onButtonPressed() {
//loadingSpinner is a ProgressBar already instantiated whit visibility GONE;
loadingSpinner.setVisibility(View.VISIBLE);
boolean resultFromAsyncTask = AnotherClass.AsyncTaskMethod();
if(resultFromAsyncTask ) {
loadingSpinner.setVisibility(View.GONE);
//do something
finish();
}else{
loadingSpinner.setVisibility(View.GONE);
//Show alert
}
}
The problem is that when I change visibility the first time nothing happens. What am I missing?
Upvotes: 1
Views: 666
Reputation: 4226
Don't over complicate things, AsyncTask
has all the methods you need to accomplish this.
Set loadingSpinner.setVisibility(View.VISIBLE);
inside onPreExecute
of your AsyncTask and set loadingSpinner.setVisibility(View.GONE);
inside onPostExecute
.
Like this:
private class YourTask extends AsyncTask<String, Void, String> {
@Override protected void onPreExecute(){
loadingSpinner.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
//Do background work
}
@Override protected void onPostExecute(String result) {
loadingSpinner.setVisibility(View.GONE);
}
}
Upvotes: 2
Reputation: 319
Building on @Notsileous, call a method from the onPostExecute
method of your AsyncTask that does some UI work. You may need to wrap that code in a runOnUiThread
for it to work.
To exemplify with your code:
public void onButtonPressed() {
//loadingSpinner is a ProgressBar already instantiated whit visibility GONE;
loadingSpinner.setVisibility(View.VISIBLE);
AnotherClass.AsyncTaskMethod().execute();
}
[...]
public void doneLoading(boolean resultFromAsyncTask ) {
runOnUiThread {
if(resultFromAsyncTask ) {
loadingSpinner.setVisibility(View.GONE);
//do something
finish();
}else{
loadingSpinner.setVisibility(View.GONE);
//Show alert
}
}
}
[...]
AsyncTask postExecuteMethod(boolean executionResult) {
doneLoading(executionResult);
}
[...]
Hope this helps clarify! :)
Upvotes: 0
Reputation: 560
Your calling an Async task but using it like a regular function. You cant base something off the result of an Async task like that, the code will just run right over it and execute the next lines.
What you want is to show the progress bar, then start your task without a return like that. You need something like a broadcast from your onPostExecute to call back to your calling class to let it know when its done.
Edit** in this case since a bool defaults to false, it is using that value in your if statement and hiding it as soon as you show it.
Upvotes: 1