我的listview的适配器有问题,我不知道在我的代码中我必须添加notifyDataSetChanged(),如果我在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. [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 :(得分:0)
它进入onPostExecute()
,因为它是在UI线程上执行的。在doInBackground()
中调用它将导致该异常。
答案 1 :(得分:-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);
}
});
}