2011-11-15 50 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

相關問題