I have a button that onclick reads and shows to the user a list with rss news. I would like to add a progress bar until finish loading. My problem is that, if I add a bar, it works properly at first but if I press the back button, the bar starts again and it can’t stop. Any help or a tutorial that demonstrates a progressbar would be appreciated. Thanks!
ProgressBar myProgressBar;
int myProgress = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main1);
Button nea = (Button) findViewById(R.id.nea);
nea.setOnClickListener(new View.OnClickListener() {
public void onClick (View view) {
setContentView(R.layout.bar);
myProgressBar=(ProgressBar)findViewById(R.id.bar);
new Thread(myThread).start();
Intent myIntent = new Intent(view.getContext(), nea.class);
startActivityForResult(myIntent, 0);
}
});
}
private Runnable myThread = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while (myProgress<100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
myProgress++;
myProgressBar.setProgress(myProgress);
}
};
};
Actually I’d implement this with an
AsyncTask, where you start the progress bar inonPreExecute(), cancel it inonPostExecute()and do the downloading indoInBackground(). If you want to update the progress value, you canpublishProgress()fromdoInBackground()which can then be updated on the ProgressBar inonProgressUpdate()https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/TweetListActivity.java#L328
shows how an example of an AsyncTask that uses those methods and which shows / hides a progress bar (
pgvariable )