【问题标题】:why can't I run a ProgressDialog inside doInBackground method of AsyncTask?为什么我不能在 AsyncTask 的 doInBackground 方法中运行 ProgressDialog?
【发布时间】:2011-11-15 22:02:54
【问题描述】:

我无法在 AsyncTask 的 doInBackground 方法中运行 ProgressDialog。它给了我以下错误:

ERROR/AndroidRuntime(12986): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

而错误就在代码的这一行:

final ProgressDialog dialog = ProgressDialog.show(GalleryView.this, "Refresh", "Loading... please wait", true);

非常感谢任何帮助。

【问题讨论】:

    标签: android android-asynctask progressdialog


    【解决方案1】:

    您可以在 onPreExecute 方法中显示进度对话框,并在 onPostExecute 方法中将其关闭。这两个方法在 UI 线程中运行。 doInBackGround 方法在另一个线程中运行。

    另一种可能性是在启动 AsyncTask 之前只显示进度对话框。我个人喜欢使用 onPreExecute 和 onPostExecute 的选项。然后进度对话框很好地链接到 AsyncTask。

    【讨论】:

      【解决方案2】:

      由于 doinbackground 不在 ui 线程上运行,因此它无法创建 UI 元素。您应该在执行 AsyncTask 之前创建进度对话框。

      【讨论】:

      • 好的,这就是我想要做的。我想在一段代码上运行进度对话框。代码完成后,我关闭对话框并想调用 AsyncTask 来刷新我的 UI。我无法做到这一点。
      【解决方案3】:

      AsyncTask 构造是关于分离后台和 UI 线程操作的。在doInBrackground 中,您不在 UI 线程中,因此您根本无法执行与 UI 相关的逻辑。执行此操作的正确位置是在 UI 线程上运行的方法中。我猜你的特殊情况是onPreExecute

      【讨论】:

        【解决方案4】:

        ProgressDialog 是 UI 代码,所以它必须发生在事件队列上。 AsyncTask 运行在事件队列之外。您可以这样进行进度对话框:

        ProgressBar progressBar = activity.findViewById(progressBarID);
        progressBar.setIndeterminate(true)
        progressBar.setVisibility(View.VISIBLE);
        AsyncTask<Void, Void, Void> aTask = new AsyncTask<Void, Void, Void>(){
         @Override
          protected Void doInBackground(Void... arg0) {
            //Do your operations here
           return null;
         }
        
         @Override
         protected void onPostExecute(Void result) {
            progressBar.setVisibility(View.GONE);
                //Wrap up anything here, like closing the popup.
         }
        };
        aTask.execute((Void)null);
        

        【讨论】:

        • 好的。现在我无法用新项目刷新我的 GalleryView。我在 onPreExecute 中调用我的进度对话框,它运行良好。在 doInBackground 中,我正在调用我的处理程序来更新 GalleryView 的适配器,以及使用适配器中的新项目更新 GalleryView 本身。但是只有当我将其中的项目移出屏幕时,画廊才会刷新。有什么帮助吗?
        • @AbhishekSharma 嗯。我们可以看到一些代码吗?也许开始一个新的问题。这样你就更有可能吸引知道答案的人。
        猜你喜欢
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多