Android: ProgressDialog doesn't show

倾然丶 夕夏残阳落幕 提交于 2019-11-27 11:33:49

you have to call pd.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.

here you can see an example:

the progressdialog is created and displayed and a thread is called to run a heavy calculation:

@Override
    public void onClick(View v) {
       pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
       Search search = new Search(   ...   );
       SearchThread searchThread = new SearchThread(search);
       searchThread.start();
    }

and here the thread:

private class SearchThread extends Thread {

        private Search search;

        public SearchThread(Search search) {
            this.search = search;
        }

        @Override
        public void run() {         
            search.search();
            handler.sendEmptyMessage(0);
        }

        private Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                displaySearchResults(search);
                pd.dismiss();
            }
        };
    }

I am giving you a solution for it, try this... First define the Progress Dialog in the Activity before onCreate() method

private ProgressDialog progressDialog;

Now in the onCreate method you might have the Any button click on which you will change the Activity on any action. Just set the Progress Bar there.

progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");

Now use thread to handle the Progress Bar to Display and hide

new Thread() 
{
    public void run() 
   {
       try
       {
           sleep(1500); 
           // do the background process or any work that takes time to see progress dialog
       }
       catch (Exception e)
       {
           Log.e("tag",e.getMessage());
       }
       // dismiss the progress dialog   
       progressDialog.dismiss();
    }
}.start();

That is all!

lory105

Progress Dialog doesn't show because you have to use a separated thread. The best practices in Android is to use AsyncTask ( highly recommended ). See also this answer.

This is also possible by using AsyncTask. This class creates a thread for you. You should subclass it and fill in the doInBackground(...) method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!