2014-10-08 93 views
0

後,我有我的適配器列表視圖我一個問題,我不知道我必須在我的代碼添加notifyDataSetChanged()始終如果我運行logcat的這段代碼是未來一個錯誤:Android的ListView控件更新的AsyncTask

java.lang.IllegalStateException: 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. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131165276, class android.widget.ListView)] 

我的AsyncTask:

class UpdateData extends AsyncTask<Void, Void, JSONArray> { 
    String result = ""; 
    JSONArray jArray = null; 


    @Override 
    protected void onPostExecute(JSONArray result) { 
     super.onPostExecute(result); 
     adapter.addAll(deptList); 
     adapter.notifyDataSetChanged(); 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
    } 


    @Override 
    protected JSONArray doInBackground(Void... arg0) { 
      .... 

     try { 
      JSONArray array = new JSONArray(result); 
      for (int i = 0; i < array.length(); i++) { 
       JSONObject j = array.getJSONObject(i); 
       EventCalendarStrings d = new EventCalendarStrings(); 
       d.name = j.optString("name", ""); 
       d.kategorie = j.optString("Art", ""); 
       deptList.add(d); 
      } 

     } catch (JSONException e) { 
      Log.e("log_tag", "No connection " + e.toString()); 
     } 
     } 
     return jArray; 
    } 
+0

確保deptList(最好使用當地的UpdateData級存儲)只在一個線程中使用。因爲它是外部變量,我懷疑它用在適配器中,因爲它的數據和...也許我錯了,但我沒有看到代碼。 – Deucalion 2014-10-08 19:50:32

+0

'deptList'是適配器的數據源嗎? – dharms 2014-10-09 14:52:43

回答

0

,因爲它是在UI線程上執行它去在onPostExecute()。在doInBackground()中調用它將導致該異常。

+0

我在onPostExecute()嘗試過,但沒有成功 – user3530080 2014-10-08 17:33:32

-1

試試這個

@Override 
    protected void onPostExecute(JSONArray result) { 
     super.onPostExecute(result); 
     runOnUiThread(new Runnable(){ 
       public void run(){ 
       adapter.addAll(deptList); 
       adapter.notifyDataSetChanged(); 

       } 
      }); 
    } 

@Override 
    protected void onPostExecute(JSONArray result) { 
     super.onPostExecute(result); 
     runOnUiThread(new Runnable(){ 
       public void run(){ 
       adapter.addAll(deptList); 
       listview.setAdapater(adapter); 
       } 
      }); 
    } 
+0

我將在哪裏添加這個codesnippet? – user3530080 2014-10-08 17:34:38

+0

'onPostExecute'已經在UI線程上執行。 – dharms 2014-10-08 17:35:26

+0

connot解決方法runOnUiThread它是說 – user3530080 2014-10-08 17:38:27