【发布时间】:2017-08-30 01:02:18
【问题描述】:
我有一个ListView 并设置了一个CustomAdapter,它显示了一个我用凌空请求调用的json 对象数组:
final ListView listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this,personList);
listView.setAdapter(adapter);
// Creating volley request obj
final JsonArrayRequest personReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
person.setfirstName(obj.getString("first_name"));
person.setlastName(obj.getString("last_name"));
//Add person to list
personList.add(person);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i(TAG, "personList items: " + personList.size());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(personReq);
使用 runnable 和处理程序,我每 5 秒发出一次此请求:
//Run volley request every 5 seconds
Runnable runnable = new Runnable() {
@Override
public void run() {
if (orderList != null) {
orderList.clear();
}
//Placing here TOO removes the last item but causes blinking
//adapter.notifyDataSetChanged();
AppController.getInstance().addToRequestQueue(personReq);
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
问题是始终保留一个项目,即使它不应该存在(由于通过单独的 volley 请求将其删除)。点击该项目会导致应用程序崩溃,并从 logcat 中显示以下内容:
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.
如您所见,我正在调用 adapter.notifyDataSetChanged();添加人员对象后直接。它工作正常,直到列表中的最后一项消失(但仍然可见)。
在 Runnable 中添加 adapter.notifyDataSetChanged(); 会清除最后一项,但会导致整个视图每 5 秒闪烁一次。
是否有可能防止这种闪烁?
【问题讨论】:
标签: android listview android-volley handler runnable