我正在使用asynctask从数据库的localhost响应中填充listview。如何在添加新项目时更新列表视图。我使用了计时器来更新列表视图,但它不会让我向上滚动,因为它会一直强制推动滚动条到底部。
class MessageTask extends AsyncTask<String, Void, List<String>> {
private final HttpClient Client = new DefaultHttpClient();
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected List<String> doInBackground(String... params) {
String output = "";
for(String out:params){
list.removeAll(list);
//Collections.reverse(list);
try{
HttpGet httpget = new HttpGet(out);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
output = Client.execute(httpget, responseHandler);
try {
JSONObject jObject= new JSONObject(output);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
//int len=menuObject.length();
//HashMap<String,ArrayList> map = new HashMap<String,ArrayList>();
for (int i = menuObject.length()-1; i>=0; i--)
{
list.add(menuObject.getJSONObject(i).getString("fk_username_c").toString()+" "+menuObject.getJSONObject(i).getString("message_c").toString());
// if(i==len){
// newtc=menuObject.getJSONObject(i).getString("timestamp_c").toString();
//}
}
/* if(oldtc==null){
oldtc=newtc;
}if
else{
}*/
adapter=new ArrayAdapter<String>(ChatActivity.this,android.R.layout.simple_list_item_1);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data ");
}
}catch(Exception e){
Log.i("Animation", "Thread exception " );
}
}
return list;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
protected void onPostExecute(List<String> list) {
//if(!oldtc.equals(newtc)){
listview.setAdapter(adapter);
adapter.clear();
listview.clearTextFilter();
adapter.addAll(list);
adapter.notifyDataSetChanged();
//}
}
}
请帮助我如何更新列表视图,只有新数据插入数据库
答案 0 :(得分:2)
添加新项目时,只需致电adapter.NotifyDataSetChanged()
答案 1 :(得分:0)
adapter.notifyDataSetChanged();
答案 2 :(得分:0)
在setAdapter
addAll
adapter.clear();
listview.clearTextFilter();
adapter.addAll(list);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
答案 3 :(得分:0)
使用广播,当新响应来自服务器时,广播此响应并在您要更新列表视图的活动中注册广播接收器。
答案 4 :(得分:0)
您无需清除适配器阵列。
只需更新适配器阵列(添加或删除项目),然后调用.notifyDataSetChanged()