2016-08-09 43 views
1

使用上的onCreate方法從服務器獲取聊天記錄到列表視圖設置線程後,向上滾動,代碼如下所有最近更新的聊天記錄工作正常,但問題是,當我向下滾動列表查看它自動滾動。列表視圖自動獲得每2秒

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

問題是您每次重新創建適配器。初始化適配器一次,只在您的onPostExecute替換數據

List chatHistories; 



    // in onPostExecute 
adapter.updateData(new_chatHistory); 




// in your adapter 
updateData(List new_chatHistory){ 

    chatHistories.addAll(new_chatHistory); 

    and adapter.notifyDataSetChanged(); 
} 
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每當您獲取數據時,請致電並致電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(); 
} 
+0

我已經實現,但其不支持working.anyway感謝。 –