Android: Progress Dialog Example



import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

    /**
     * we are going to create a Handler object on UI (main) thread
     * and thus we will be able to post messages (run code) on UI thread
     */
    Handler handler;

    // this is our progressDialog
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // create the Handler object on thread-A will enable you to get
        // a reference of thread-A from thread-B
        handler = new Handler();

        // starting the time consuming long task
        startTimeConsumingTask ();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void startTimeConsumingTask() {

        // display the progressbar on the screen
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("loading...");
        progressDialog.show();

        // start the time consuming task in a new thread
        Thread thread = new Thread() {

            public void run () {

                // this is the time consuming task (like, network call, database call)
                for ( int i = 0; i < 1000000; i++ ) {

                    // demo time consuming task.
                    Log.i(MainActivity.class.getSimpleName(), "Now we are at: " + i);
                }

                // Now we are on a different thread than UI thread
                // and we would like to update our UI, as this task is completed
                handler.post(new Runnable() {
                    @Override
                    public void run() {

                        // Update your UI or do any Post job after the time consuming task
                        updateUI();

                        // remember to dismiss the progress dialog on UI thread
                        progressDialog.dismiss();

                    }
                });

            }
        };

        thread.start();
    }

    private void updateUI () {
        // update your UI after long running task
    }
    
}

3 thoughts on “Android: Progress Dialog Example

Leave a Reply

Fill in your details below or click an icon to log in:

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 )

Google+ photo

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

Connecting to %s