我正在使用 Service 从服务器获取消息并存储在本地数据库中。如果我不这样做的话,我需要为截击响应创建新的线程,这样 UI 会滞后很多,但 ListView 正在更新。现在,在创建新线程后,UI 不再滞后,但不会更新 ListView 。下面是我的服务类代码。
聊天服务.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();
}
});
}`
另一方面,在 fragment 中我想通过以下代码通知我的 ListView 数据库已更新。
聊天 fragment .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 通知我的 ListView 。
聊天列表适配器.java
public void updateChatList(ArrayList<ChatListDataResponse> numbers){
listDataResponses.clear();
listDataResponses.addAll(numbers);
this.notifyDataSetChanged();
this.notifyDataSetInvalidated();
}
- 我得到的结果:第一次将 api 响应存储到本地数据库后,listview 保持空白。每次调用 ChatService 时, ListView 都不会更新。
- 我想要的结果:我想在调用 ChatService 时通知 ListView 。
最佳答案
尝试使用 Handler 来更新 UI,因为 Threads 不确认 UI 相关工作的工作:
new Handler().post(new Runnable() {
public void run() {
//UI updation code
}
});
或尝试:
runOnUiThread(new Runnable() {
public void run() {
//UI updation code
}
});
关于android - notifyDataSetChanged 不适用于 Thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41348840/