2012-07-11 35 views
2

我正在嘗試更新我的列表並在我的活動中顯示更新的列表。每次我這樣做,我得到以下錯誤Android如何正確通知數據集更改爲ListView

The content of the adapter has changed but ListView did not receive a notification. 
Make sure the content of your adapter is not modified from a background thread, 
but only from the UI thread. 

這是我的代碼,我使用AsyncTask來實現此任務。我在我的適配器上調用了notifyDataSetChanged(),但它似乎不起作用。我究竟做錯了什麼?

class MyTask extends AsyncTask<Context, Integer, String> { 

    @Override 
    protected String doInBackground(Context... params) { 
     GregorianCalendar currentDateclone = (GregorianCalendar) currentDate.clone(); 
     ListPopulater2.listPopulate(currentDateclone, 7, items, Id); 
        //method to update list info 




    } 

    // -- gets called just before thread begins 
    @Override 
    protected void onPreExecute() { 
     progressdialog = ProgressDialog.show(SectionListExampleActivity.this, "", "Loading..."); //display progress bar 
     super.onPreExecute(); 

    } 

    // -- called as soon as doInBackground method completes 
    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     Log.d("postExecute", "here"); 
        adapter.notifyDataSetChanged(); 

     progressdialog.cancel(); 
    } 
} 
+1

與你的問題沒有關係,但你爲什麼在'onPostExecute(...)'中使用'runOnUiThread(...)'?無論如何,'AsyncTask'的所有方法(除了'doInBackground(...)')都在UI線程上運行。 – Squonk 2012-07-11 00:46:41

+0

我剛剛嘗試的東西,沒有它的工作原理。我只是刪除它清晰 – 2012-07-11 00:49:45

回答

3

嘗試移動:

ListPopulater2.listPopulate(currentDateclone, 7, items, Id); 

onPostExecute

這個原因是因爲您在完成所有背景活動後需要更新列表,而不是在執行此操作時。您可以使用onProgressUpdate,但這是用於您的進度對話框。更新列表視圖應在完成所有數據後完成,否則,由於UI在主線程上運行,並且您嘗試使用後臺線程更新,您會得到您所做的錯誤。

至於進度對話框,有一個目的。如果你正在做的事情需要一段時間才能完成,對話框會告訴用戶你有多接近完成後臺任務。

希望是有道理的。

+0

這工作,但任何解釋爲什麼這將是?這種殺死進度對象的目的 – 2012-07-11 00:17:38

+0

我理解你在說什麼,但是如果我將填充方法移動到onPostExecute,那麼在doInBackground方法中沒有任何操作。我對AsyncTask的理解是加載可以在後臺完成,然後一旦完成onPostExecute被調用。 – 2012-07-11 01:01:09

+0

我認爲在方法listPopulate你試圖更新一些數據模型沒有得到反映onPostExecute可能是因爲doInBackground在後臺線程中運行? – anargund 2012-07-11 01:04:28

2

當你想要做一些處理UI的事情時,你必須在UI線程中完成這個任務。 因此,對於這一點,你可以使用2個方法:

  1. 使用runOnUi()方法
  2. 使用OnPostExecute()方法

而且你在哪裏設置你在那個地方使用notifyDatasetchanged()適配器在listView中。

相關問題