ProgressDialog无法显示

时间:2018-01-05 14:51:50

标签: android progressdialog

我有一个进度对话框,我希望它在我的方法执行完毕后显示和解除。现在,我有这个:

progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("Downloading...");
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            DownloadMethod(s);
                            progressDialog.dismiss();
                        }catch (Exception e){
                            Toast.makeText(prefs.this, "We can't reach the data...Try again", Toast.LENGTH_SHORT).show();
                        }

                    }
                }).start();

我的方法DownloadMethod已执行但从未显示对话框。

3 个答案:

答案 0 :(得分:4)

实际上,它必须通过progressDialog.dismiss();调用抛出异常,因为您无法从工作线程更新UI,而是使用AsyncTask

例如将参数传递给构造函数

 private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
    TypeOf_S s;

     public DownloadFilesTask(TypeOf_S s){
        this.s = s;
     }

     @Override
     protected Void doInBackground(Void... obj) {
         DownloadMethod(s);
         return null;
     }

     @Override
     protected void onPostExecute(Void result) {
         progressDialog.dismiss();
     }
 }

并将其称为new DownloadFilesTask(s).execute();

或使用通用参数

private class DownloadFilesTask extends AsyncTask<TypeOf_S, Void, Void> {

     @Override
     protected Void doInBackground(TypeOf_S... obj) {
         DownloadMethod(obj[0]);
         return null;
     }

     @Override
     protected void onPostExecute(Void result) {
         progressDialog.dismiss();
     }
 }

并将其称为new DownloadFilesTask().execute(s);

答案 1 :(得分:0)

progressDialog.dismiss();抛出异常,因此请将代码移到runOnUiThread()方法中,如下所示:

 runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                       progressDialog.dismiss();
                    }
                });

答案 2 :(得分:0)

根据Pavneet的建议,您可以使用异步任务,其中AsyncTask<String, void, String>对应于输入类型进度值,最后是您感兴趣的结果值,因此相应地给出数据类型。

    private class DownloadFilesTask extends AsyncTask<String, void, String> {
     protected String doInBackground(String... urls) {
         //here do the actual downloading instead of calling the DownloadMethod(s)
     }

     protected void onPreExecute() {
         //here show the dialog
         progressDialog.show();
     }

     protected void onPostExecute(String result) {
         //here hide the dialog
         progressDialog.dismiss();
     }
 }

如果您正在调用下载功能,请调用此

progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Downloading...");
new DownloadFilesTask().execute(s);
//here s is assumed to be string type you can give anything