Search code examples
javaandroiddialogloadingprogress

Display loading dialog while running method in Android?


I have a method setup that takes about 3-5 seconds to run (because it does something online) and I would like to show a loading dialog, but I cant figure out how to do it, I tried starting the loading dialod before I called the method then tried to dismiss it right after like this:

dialog.show();
myMethod();
dialog.cancel();

But that didn't work, does anyone have any suggestions?


Solution

  • AsyncTask is my Favouite but you may use Handlers too :)

    Invest your time to go through this nice blog.

    Below snippet will help you.

        package org.sample;
    
        import android.app.Activity;
        import android.app.ProgressDialog;
        import android.os.Bundle;
        import android.os.Handler;
    
        public class Hello extends Activity {
    
            private Handler handler;
            private ProgressDialog dialog;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                dialog = new ProgressDialog(this);
                dialog.setMessage("Please Wait!!");
                dialog.setCancelable(false);
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
    
                new Thread() {
                    public void run() {
                        // Do operation here.
                        // ...
                        // ...
                        // and then mark handler to notify to main thread 
                        // to  remove  progressbar
                        //
                        // handler.sendEmptyMessage(0);
                        //
                        // Or if you want to access UI elements here then
                        //
                        // runOnUiThread(new Runnable() {
                        //
                        //     public void run() {
                        //         Now here you can interact 
                        //         with ui elemements.
                        //
                        //     }
                        // });
                    }
                }.start();
    
                handler = new Handler() {
                    public void handleMessage(android.os.Message msg) {
                        dialog.dismiss();
                    };
                };
            }
        }