我正在使用服務從服務器獲取消息並存儲在本地數據庫中。如果我不這麼做,我需要創建新的Thread for volley response。UI如此落後,但listview正在更新。現在創建新的線程後,用戶界面不再滯後,但它不更新列表視圖。以下是我的服務類代碼。notifyDataSetChanged不適用於線程
ChatService.java
StringRequest stringRequest=new StringRequest(Request.Method.GET, url.replaceAll(" ","%20"), new Response.Listener<String>() {
@Override
public void onResponse(final String response) {
networkThread=new Thread(new Runnable() {
@Override
public void run() {
Gson gson=new Gson();
chatResponse=gson.fromJson(response,GetAllChatResponse.class);
for (Object obj:chatResponse.getData()) {
Log.d("conversation response",""+((ChatDataResponse) obj).getMessage());
sqLiteDataProvider.insertMessage(true,(ChatDataResponse) obj);
}
Log.d("conver","ok");
sendWaResult();
}
});
networkThread.start();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("convo error",""+error.getMessage());
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
public void sendWaResult(){
final Intent intent=new Intent(KYOWA_RESULT);
try{
Looper.prepare();
} catch (Exception e) {}
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
waBroadcastManager.sendBroadcast(intent);
stopSelf();
}
});
}`
雖然在片段另一方面我想通知我的列表視圖,數據庫已被下面的代碼更新。
ChatFragment.java
receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ChatFragment.this.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
getChat();
}
});
}
};
private void getChat() {
new AsyncTask<Void,Void,ArrayList<ChatListDataResponse>>(){
@Override
protected ArrayList<ChatListDataResponse> doInBackground(Void... voids) {
return sqLiteDataProvider.getChatList();
}
protected void onPostExecute(ArrayList<ChatListDataResponse> list)
{
listDataResponses = list;
if (chatListAdapter==null){
chatListAdapter=new ChatListAdapter(getContext(),listDataResponses);
mListView.setAdapter(chatListAdapter);
}else {
chatListAdapter.updateChatList(listDataResponses);
}
}
}.execute();
而且我通過定製BaseAdapter通知我的列表視圖。
ChatListAdapter.java
public void updateChatList(ArrayList<ChatListDataResponse> numbers){
listDataResponses.clear();
listDataResponses.addAll(numbers);
this.notifyDataSetChanged();
this.notifyDataSetInvalidated();
}
- 結果我得到:對於第一次存儲數據庫列表視圖保持空白API響應納入當地後。每次調用ChatService時,listview都不會更新。
- 結果我想:每當ChatService被調用時我想通知列表視圖。
你解決了你的問題嗎? –