Nugget Post: Android Process Dialog

A lesson that took me an hour to figure out: android progress dialogues will only be displayed on the UI if called/shown in a thread or async task. Basically when try to call a progress dialog directly from a fragment, android would simply not show the dialog.

Example of the android progress dialog (indeterminate)
Example of the android progress dialog (indeterminate)

So the code would look something like this:


uploadButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
//perform upload action
Thread thread = new Thread()
{
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setTitle("File Upload");
progressDialog.setMessage("Please Wait…");
progressDialog.isIndeterminate();
progressDialog.show();
}
});
uploadFile();
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.dismiss();
}
});
}
};
thread.start();
}
});

 

The code shows how to attach a listener that will trigger a sequence of events when a button (uploadButton) is clicked. The sequence is:

  • Initialize the progessDialog (so we can refer to the variable across threads)
  • Start a new thread
  • Within the thread, prepare the look and feel of the progress dialog and display it in the UI thread
  • Do your long task (uploadFile)
  • Dismiss the progress dialog in the UI thread
Advertisement
Privacy Settings

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.