Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress Dialog for AsyncTask - Android

I'm trying to show a progress dialog while the twitter feed is loading up...However the progress dialog remains on screen when the twitter feed appears. Any help is much appreciated.

public class MainActivity extends ListActivity {

    final static String twitterScreenName = "CFABUK";
    final static String TAG = "MainActivity";
    private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
    boolean done;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        done=false;
        AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
        if (androidNetworkUtility.isConnected(this)) {
            TwitterAsyncTask syn=new TwitterAsyncTask();
            syn.execute(twitterScreenName,this);


            ProgressDialog pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("loading");
            pd.show();

            do {
                if(!(syn.getStatus()==AsyncTask.Status.RUNNING)) {
                pd.dismiss();
                pd.cancel();
                done=true;
                }
            } while(done=false);


        } else {
            Log.v(TAG, "Network not Available!");
        }
    }
}
like image 904
user3156801 Avatar asked Jan 09 '23 18:01

user3156801


2 Answers

You must call ProgressDialog show() method on AsyncTasks onPreExecute(). For example:

class MyTask extends AsyncTask<Void, Void, Void> {
 ProgressDialog pd;
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
       pd = new ProgressDialog(MainActivity.this);
       pd.setMessage("loading");
       pd.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
      // Do your request
    }

    @Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      if (pd != null)
      {
         pd.dismiss();
      }
    }
  }
like image 195
Slampy Avatar answered Jan 17 '23 16:01

Slampy


You must use a onPreExecute and onPostExecute of AsyncTask class. For example:

class AsyncData extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // init progressdialog
    }


    @Override
    protected Void doInBackground(Void... arg0) {
        // get data
        return null;
    }


    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // dismiss dialog
    }
}
like image 42
Yeray Avatar answered Jan 17 '23 16:01

Yeray