Thursday, December 30, 2010

Show a progress dialog when a thread is running

  We can easily show a progress dialog with Async task. But asyn task has its own drawbacks. There can be no ui's and the task can be executed only once.
   Better way is to use a thread for lengthy processing and show a progess dialog in the ui thread. (I struggled quite a bit. My progress dialog would keep on spinning infinitely :-( )

e.g.

//this is your main activity thread
handler = new FeedReadHandler();
....
.....

pd = ProgessDialog.show(context,"Loading","Loading the file. please wait...");
Thread background = new Thread(new Runnable(){     

                        @Override
                        public void run() {
                            readFeed(nameUrl);
                            Message msg = handler.obtainMessage();
                            msg.arg1=FEED_LOAD_FINISHED;
                            handler.sendMessage(msg);
                           
                        }
                       
                    });
                    background.start();
                    -.....
......

  Now you are starting a progress dialog and then starting the thread called background to run the function readFeed. When the function is completed, the thread sends a message to the handler.

Here is the handler code
 public class FeedReadHandler extends Handler{
       @Override
       public void handleMessage(Message msg){
           Log.d("SHOWRSS","i think i received a message");
           if(msg.arg1==FEED_LOAD_FINISHED){
               pd.dismiss();
               .....

               .....
              
           }
          
       }
   }

So the handler when receives the message from our background thread, on receiving this message it closes the progress- dialog.