Shraddha
Shraddha

Reputation: 1052

How to display Progressbar when Webservice is loading data?

I am using a webservice that fetch the n number of records from webservice. I am using WS Client for calling webservices. Now I would like to have a progress bar that displays how many out of the n number of data has loaded. Is there any possibilities to achieve this? I am using AsyncTask to call WS in background.

Upvotes: 1

Views: 2960

Answers (2)

jeet
jeet

Reputation: 29199

To perform this kind of progress updates, you need to make your webservice to return results in parts not fully. Like for n number of records, webservice can return results n/p, one time, and use publishProgress method to notify event thread about percentage of task, and postEexcute about completion of webservice calling and parsing.

Upvotes: 1

Aalok Sharma
Aalok Sharma

Reputation: 1025

Try something like this ,,this basically shows an example of updating the progress bar while an async task is running

  public class AndroidAsyncTaskProgressBar extends Activity {

 ProgressBar progressBar;
 Button buttonStartProgress;

 public class BackgroundAsyncTask extends
    AsyncTask<Void, Integer, Void> {

  int myProgress;

  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   Toast.makeText(AndroidAsyncTaskProgressBar.this,
         "onPostExecute", Toast.LENGTH_LONG).show();
   buttonStartProgress.setClickable(true);
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   Toast.makeText(AndroidAsyncTaskProgressBar.this,
         "onPreExecute", Toast.LENGTH_LONG).show();
   myProgress = 0;
  }

  @Override
  protected Void doInBackground(Void... params) {
   // TODO Auto-generated method stub
   while(myProgress<100){
    myProgress++;
    publishProgress(myProgress);
       SystemClock.sleep(100);
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
   // TODO Auto-generated method stub
   progressBar.setProgress(values[0]);
  }

 }


 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     buttonStartProgress = (Button)findViewById(R.id.startprogress);
     progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
     progressBar.setProgress(0);

     buttonStartProgress.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    new BackgroundAsyncTask().execute();
    buttonStartProgress.setClickable(false);
   }});
 }
}

Upvotes: 7

Related Questions