Dec 20, 2010

Update ProgressBar inside AsyncTask

Update ProgressBar inside AsyncTask

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<ProgressBar
    android:id="@+id/progressbar" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    style="?android:attr/progressBarStyleHorizontal"
    android:max="100"
    android:progress="0"
    />
<Button
    android:id="@+id/start"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="- Start -"
    />
</LinearLayout>


package com.AndroidProgressBar;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class AndroidProgressBar extends Activity {
 
 Button buttonStart;
 ProgressBar progressBar;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonStart = (Button)findViewById(R.id.start);
        progressBar = (ProgressBar)findViewById(R.id.progressbar);
        
        buttonStart.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    buttonStart.setClickable(false);
    new asyncTaskUpdateProgress().execute();
   }
         
        });
        
    }
    
    public class asyncTaskUpdateProgress extends AsyncTask<Void, Integer, Void> {

     int progress;
     
  @Override
  protected void onPostExecute(Void result) {
   // TODO Auto-generated method stub
   buttonStart.setClickable(true);
  }

  @Override
  protected void onPreExecute() {
   // TODO Auto-generated method stub
   progress = 0;
  }

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

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


Related: Implement vertical ProgressBar

1 comment:

Infolinks In Text Ads