android開發中不免遇到listview刷新數據出現異常

異常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.java

 

解決辦法分析:異步

既然與listView綁定了的list發生了變化而沒來得及通知listView致使了上述的異常,那咱們就針對這一點,只要listView與list綁定後,在listView顯示以前不要讓list發現變化就好了。作法有不少種,我我的的作法是這樣子的:this

首先,定義一個獨立的List:spa

private List<Map<String,Object>> data = null;線程

接着,在onCreate中初始化它(固然,你也能夠在每次用到它的時候初始化它,不過這樣子會初始化不少歌對象,浪費內存,不推薦):對象

data = new ArrayList<Map<String,Object>>();ip

而後,在建立adapter以前,把list中數據放入到集合data中,注意千萬不要直接賦值:data = list(這是錯誤的,由於這樣data也指向了list所在的內存地址,即data跟list是同一個對象,list改變的話data也跟着改變);應該這麼作:內存

data.clear();//要先清空data中的數據,避免把list中的數據重複放入data中。源碼

data.addAll(list);//這樣作,list中的數據就放入到data中,以後list在後臺線程中改變,但data不會改變,這時,你再it

SimpleAdapter adapter = new SimpleAdapter(LocalActivity.this,data,R.layout.local_music_list,new String[] {"local_name","local_size"}, new int[]{R.id.local_name,R.id.local_size});

listView與data綁定,就不會發生上述異常了!

 

幾句重要源碼:

一、第一步代碼:

private void initData() {
  storeInfoList = new ArrayList<StoreSimpleInfoEntity>();    // 實例化對象
  sendRequestGetNearShop(flag, firstPage);   //  異步請求數據
  myAdapter = new StoreInfoAdapter3(NearByStoreActivity.this,storeInfoList);  // 初始化適配器
  curNewStoreList.setAdapter(myAdapter);
  curNewStoreList.setPullLoadEnable(true);
  curNewStoreList.setXListViewListener(this);
  curNewStoreList.setOnItemClickListener(this);
 }

二、第二步代碼:

private Handler mHandler = new Handler() {
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case SUCCESS:
    storeInfoList.addAll(storeInfo);   // 數據成功返回後將返回數據添加到定義好的storeInfoList中
    refreshAdapter(storeInfoList);  
    onLoad();
    break;
   case FAIL:
    break;
   case CLOSE:
    break;
   }
  };
 };

三、第三步代碼:

/**
  *
  * @Title: refreshAdapter
  * @Description:刷新myAdapter適配器
  * @param
  * @return
  * @exception
  * 2013-11-14 下午3:40:13
  */
 private void refreshAdapter(final List<StoreSimpleInfoEntity> items) {
  runOnUiThread(new Runnable() {
   public void run() {
    myAdapter.refreshAdapter(items);
   }
  });
 }

 

四、第四步:

適配器中的代碼:

/*
  * 提供適配器刷新方法
  */
 public synchronized   void refreshAdapter(List<StoreSimpleInfoEntity> items) {
  list = items;
        notifyDataSetChanged();
    }

就這幾步。

寫代碼時,認真檢查代碼邏輯。

相關文章
相關標籤/搜索