开发者

Progress bar on a button click

In my app, at the click of a button, the app does some processing, sends some data over the network and then stops. As it takes some time, I tried putting in a progress bar. The code for the progress bar is at the beginning of the onclick listener for the button. After the progress bar code, the processing and sending data over the network take开发者_JS百科s place. But the progress bar is not visible at all. Do I need to necessarily show the progress bar in a separate thread?

This is what i have used to show the progress bar

final ProgressDialog pd=new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setMessage("Please wait..");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();


use the AsyncTask class which was used to do process in background and you can also showing up your progressbar there

Here is the simple snippet of code for AsyncTask

class BackgroundProcess extends AsyncTask<Void,Void,Void>{
   private ProgressDialog progress;
   public doInBackground(Void...arg){
        publishProgress();
        // do your processing here like sending data or downloading etc.
   }
   @Override
   protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
    progress = ProgressDialog.show(YourActivity.this, "", "Wait...");       
   }
   @Override
   protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if(progress!=null)
        progress.dismiss();
    progress = null;
   }
}

now initialize and execute it in button onclick listener like this way

new BackgroundProcess().execute();

now progressdialog will be publish and appear on the screen and when process was completed then from the onPostExecute() just dismiss the progress dialog


I pasted your code into my application, and it works just fine. Are you calling all of that from the UI Thread? If you are doing some heavy processing and data transmission, make sure not to run that on the UI thread. Make an AsyncTask to handle the network stuff.

EDIT: I moved it into its own thread, and it no longer works, so make sure it's being called from the UI Thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜