android - notifyDataSetChanged 不适用于 Thread

标签 android multithreading listview custom-adapter notifydatasetchanged

我正在使用 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/

相关文章:

java - Android添加名字,中间名和姓氏的第一个字符的值

Android - ClipDrawable、ScaleDrawable,它是如何工作的?

c++ - 使用 sleep() 时生产者消费者(使用 Monitor)代码不工作?

multithreading - 如何制作原子指令

c# - 多线程访问内存中的大型字典对象 - 瓶颈?

javascript - onChange仅在2次文本输入后触发

Android:notifyDataSetChanged()在方向改变后不更新 ListView

android - 将源附加到 kotlin 库项目不显示在 AS

android - 如何动态显示编辑文本框

android - 单选按钮在 ListView 中无法正常工作