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

Leave a comment

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