定义一个临时的数组变量承接数据,ListView的数据以及通知数据更新要放到同一个线程(主线程)。避免出现异常"The content of the adapter has changed but ListView did not receive a notification"。
public class WordFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2 { private List<Word> dataList = new ArrayList<>(); private List<Word> dataListTemp = new ArrayList<>(); // 定义一个临时的数组变量承接数据,ListView的数据以及通知数据更新要放到同一个线程(主线程)。避免出现异常"The content of the adapter has changed but ListView did not receive a notification"。 private int pageIndex = 1; private int pageSize = 150; private final int MESSAGE_GET_LIST_DATA = 0; private String userID; private int type = 0; // 信息接收处理-成功 @Override public void handlerAPIRequestSucceed(Message msg) { switch (msg.what) { case MESSAGE_GET_LIST_DATA: handle_getListData(msg); break; default: break; } } // 事件------------------------------开始 private void getListData() { new Thread(new Runnable() { @Override public void run() { String response = api_word.list(String.valueOf(pageIndex), String.valueOf(pageSize), String.valueOf(type)); try { JSONArray ja = new JSONArray(response); Word word; dataListTemp.clear(); for (int i = 0; i < ja.length(); i++) { JSONObject jo = ja.getJSONObject(i); // 转换成JSONObject对象 word = new Word( jo.getString("id"), jo.getString("query"), jo.getString("speakUrl"), jo.getString("translation"), jo.getString("phonetic"), jo.getString("ukPhonetic"), jo.getString("usPhonetic")); dataListTemp.add(word); } } catch (JSONException e) { e.printStackTrace(); } // 在子线程中将Message对象发出去 Message message = new Message(); message.what = MESSAGE_GET_LIST_DATA; message.obj = null; // handler.sendMessage(message); } }).start(); } // 事件------------------------------结束 // 处理------------------------------开始 // 返回结果处理-获取列表数据 private void handle_getListData(Message msg) { // 收起下拉控件的等待图标 listView.onRefreshComplete(); if (1 == pageIndex) { // 如果是第一页(即刷新),则清空原有数据 dataList.clear(); } dataList.addAll(dataListTemp); adapter.notifyDataSetChanged(); } // 处理------------------------------结束 }