Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating a ProgressDialog

Published? true
FormatLanguage: WikiFormat

Problem:

Making the user aware of background processing happening in the application.

Solution:

Show a ProgressDialog while the processing is being carried out.

Discussion:

We provide a button that on being clicked shows a ProgressDialog. In the ProgressDialog we set the title as 'Please Wait' and content as 'Processing Information..'. After this we create a new thread and start the thread's execution. In the run() method (which gets executed once the thread gets started) we call the sleep method for 4 seconds. After these 4 seconds expire the ProgressDialog is dismissed and the text in TextView gets changed.

complete = (TextView) this.findViewById(R.id.complete);
complete.setText("Press the Button to start Processing");
processing = (Button)findViewById(R.id.processing);
processing.setOnClickListener(new View.OnClickListener() {
			
	@Override
	public void onClick(View arg0) {
		progressDialog = ProgressDialog.show(ProgressDialogExp.this, "Please Wait", "Processing Information..", true,false);
        Thread thread = new Thread(ProgressDialogExp.this);
        thread.start();
	}
});

A Handler is used so as to update the UI once thread execution finishes. So we send an empty message to the handler after thread execution completes and then in the Handler we dismiss the ProgressDialog and update the text of the TextView.

public void run() {
	try {
		Thread.sleep(4000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
       handler.sendEmptyMessage(0);		
}

private Handler handler = new Handler() {
		@Override
	    public void handleMessage(Message msg) {
	    progressDialog.dismiss();
	    complete.setText("Processing Finished");
   }
};

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LMTE2NDcyMDEtNGMzMS00MzI4LTgyNGUtNzliZmY4ZjhhOWE2&hl=en_US.