Threads - the progress bar and post-thread action

Quickly share your Android Code Snippets here...

Threads - the progress bar and post-thread action

Postby kenhall » Fri Dec 05, 2008 12:59 pm

The Progress bar must update in a separate thread. So you need to do something like this -

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         final ProgressBar progress = (ProgressBar)findViewById(R.id.create_progress);
  2.  
  3.         progress.setMax(100);
  4.  
  5.         progress.setProgress(0);
  6.  
  7.         new Thread(new Runnable() {
  8.  
  9.            public void run() {
  10.  
  11.                    for (int i=0;i<100;i++) {
  12.  
  13.                          progress.setProgress(i);
  14.  
  15.                     }        
  16.  
  17.             }
  18.  
  19.         }).start();
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


Note that anything that you want to use in a thread that you declare outside of the thread must be declared as 'final'.

The next issue arises if you want to update a view after the thread has completed. You can't amend the view if it has been created outside the thread so to achieve this you have to use a Handler e.g.

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.     public void myTest() {
  2.  
  3.         final Handler aHandler = new Handler();
  4.  
  5.  
  6.  
  7.         final Runnable updateResults = new Runnable() {
  8.  
  9.             public void run() {
  10.  
  11.                 updateResults();
  12.  
  13.             }
  14.  
  15.         };
  16.  
  17.  
  18.  
  19.         final ProgressBar progress = (ProgressBar)findViewById(R.id.create_progress);
  20.  
  21.         progress.setMax(100);
  22.  
  23.         progress.setProgress(0);
  24.  
  25.         new Thread(new Runnable() {
  26.  
  27.            public void run() {
  28.  
  29.                    for (int i=0;i<100;i++) {
  30.  
  31.                          progress.setProgress(i);
  32.  
  33.                     }        
  34.  
  35.                     //Now we call the handler to update the results
  36.  
  37.                     aHandler.post(updateResults);
  38.  
  39.             }
  40.  
  41.         }).start();
  42.  
  43.    }
  44.  
  45.  
  46.  
  47.     public  final void updateResults() {
  48.  
  49.         ((TextView)findViewById(R.id.result)).setText("ProgressComplete");
  50.  
  51.     }
  52.  
  53.  
  54.  
  55.        
Parsed in 0.034 seconds, using GeSHi 1.0.8.4
Virtual Machinery
BTree implementations for Java platforms (Desktop, Server and Mobile)
JHawk - the premier Java metrics tool
http://www.virtualmachinery.com
kenhall
Freshman
Freshman
 
Posts: 4
Joined: Fri Dec 05, 2008 11:46 am

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: Google Feedfetcher and 6 guests