2011-11-15 52 views
0

我无法在AsyncTask的doInBackground方法内运行ProgressDialog。它给了我下面的错误:为什么我不能在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); 

任何帮助非常赞赏。

回答

1

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

+0

好的,这就是我想要做的。我想在一段代码上运行progressdialog。一旦代码完成,我关闭对话框并想调用AsyncTask来刷新我的UI。我无法做到这一点。 –

1

AsyncTask构造是关于分离背景和UI线程操作。在doInBrackground之内,您不在UI线程中,所以您根本无法完成与UI相关的逻辑。正确的位置是在UI线程上运行的方法。我猜你的具体情况是这样的地方是onPreExecute

3

您可以在onPreExecute方法中显示progressdialog,并在onPostExecute方法中关闭它。这两个方法在UI线程中运行。 doInBackGround方法在另一个线程中运行。

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

1

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); 
+0

好的。现在我无法使用新项目刷新我的GalleryView。我在onPreExecute中调用我的进度对话框,它运行正常。在doInBackground中,我打电话给我的处理程序来更新适用于GalleryView的适配器,以及Gallery适配器中的新项目。但画廊只有在将其中的物品移出屏幕时才会刷新。任何帮助? –

+0

@AbhishekSharma嗯。我们可以看到一些代码吗?也许开始一个新的问题。这样你就更有可能吸引知道答案的人。 – heneryville

相关问题