使用Oncreate方法从服务器获取聊天记录以在listview上设置的线程,代码如下:
Runnable run = new Runnable() {
public void run() {
// new Comments(false).execute();
new GetChatFromServer().execute();
handler.postDelayed(this, 1600);
}
};
runOnUiThread(run);
它正在调用GetChatFromServer类以使所有最近更新的聊天记录正常工作,但问题是当我向下滚动列表视图时它会自动向上滚动。
class GetChatFromServer extends AsyncTask<String, Integer, Double> {
String chathistory;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
System.out.println("My url is>>>>" + chatHistoryUrl);
}
@SuppressWarnings("unchecked")
@Override
protected Double doInBackground(String... params)
throws ArrayIndexOutOfBoundsException {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(chatHistoryUrl,
ServiceHandler.GET);
chathistory = "{\"chatHistories\":" + jsonStr + "}";
Gson gson = new Gson();
Type listType = new TypeToken<List<ChatHistory>>() {
}.getType();
chatHistories = (ArrayList<ChatHistory>) gson.fromJson(jsonStr,
listType);
// ChatModel res = gson.fromJson(chathistory, ChatModel.class);
return null;
}
protected void onProgressUpdate(Integer... progress) {
// pb.setProgress(progress[0]);
}
@Override
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mAdapter = new ChatMessageAdapter(ChatMainActivity.this,
chatHistories, sourceId);
chatList.setAdapter(mAdapter);
}
}
如果有人可以帮助解决我的问题。提前谢谢。
答案 0 :(得分:4)
问题出在这里
@Override
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mAdapter = new ChatMessageAdapter(ChatMainActivity.this,
chatHistories, sourceId);
chatList.setAdapter(mAdapter);
}
每当您从服务器获取数据时,您一次又一次地呼叫setAdapter
,您需要做的是在OnCreate
中设置适配器并在您获取数据时调用mAdapter.notifyDataSetChanged
。
以下是示例:
String chathistory;
ChatMessageAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
........
mAdapter = new ChatMessageAdapter(ChatMainActivity.this, chatHistories, sourceId);
chatList.setAdapter(mAdapter);
}
并在onPostExecute
@Override
protected void onPostExecute(Double result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
答案 1 :(得分:0)
问题是你每次都在重新创建适配器。初始化适配器一次并仅替换onPostExecute
中的数据List chatHistories;
// in onPostExecute
adapter.updateData(new_chatHistory);
// in your adapter
updateData(List new_chatHistory){
chatHistories.addAll(new_chatHistory);
and adapter.notifyDataSetChanged();
}