适配器未刷新

时间:2013-09-25 11:18:03

标签: android android-listview android-adapter

我有三个片段的主要活动。第一个片段是listview。我在片段的onCreateView方法中填充它,如下所示:

private ArrayList<MobileNETDistinctChatInfo> m_parts = new ArrayList<MobileNETDistinctChatInfo>();
public MobileNETDistinctChatInfoAdapter m_adapter;
public ListView list;
public String logged_user;

onCreateView(){
    LinearLayout view = (LinearLayout) inflater.inflate(R.layout.tab1, container, false);
    list = (ListView)view.findViewById(R.id.chats_list)

    m_parts = db.MESSAGES_getAllDistinctChatInfo(logged_user); 

    // adapter extends the ArrayAdapter 
    m_adapter = new MobileNETDistinctChatInfoAdapter(getActivity(), R.layout.chatlist_list_item, m_parts);

    list.setAdapter(m_adapter);

    return view;

}

我想在fragment1中的onResume()方法中刷新listview,但我无法让它工作。我尝试了这两种方法(如果我使用第一种方法,没有任何反应。如果我使用第二种方法,应用程序崩溃,返回NullPointerException):

# 1
public void onResume() {
    super.onResume();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            m_adapter.notifyDataSetChanged();
        }
    }
}

# 2
public void onResume() {
    super.onResume();

    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            m_parts.clear();
            m_parts = db.MESSAGES_getAllDistinctChatInfo(logged_user);

            ListView list = (ListView) getActivity().findViewById(R.id.chats_list);
            MobileNETDistinctChatInfoAdapter caa = (MobileNETDistinctChatInfoAdapter) list.getAdapter();
            caa.clear();

            for(MobileNETDistinctChatInfo el : m_parts){
                caa.add(el);
            }

            list.setAdapter(caa);
        }
    }
}

我在OnResume()中打印了m_parts和m_adapter的大小,而似乎没有刷新适配器,但是m_parts是。有人知道为什么,或者我怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

您正在一个单独的线程中运行m_adapter.notifyDataSetChanged(),这导致在实际修改或更新列表之前执行刷新列表。

如果您对代码进行了debeg,那么您可以看到它正常工作,因为该线程有足够的时间来执行。