ChatApp - 适配器未更新

时间:2016-03-11 04:45:48

标签: java android listview adapter baseadapter

我正在使用聊天应用,我需要每隔一秒刷新一次列表。我正在使用处理程序重复调用该方法,但它没有更新ListView。我正在调用该方法中更改的通知数据集。

Messages.java

public class Messages extends Activity {
    ListView chatview;
    ChatAdapter chatAdapter;
    List<CBData> chatdata;
    public int APP_REFRESH_TIME_IN_SEC = 1;
    Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_details);
        chatview = (ListView) findViewById(R.id.chatview);
        chatdata = new ArrayList<CBData>();
        chatAdapter = new ChatAdapter(getApplicationContext(), chatdata);
        chatview.setAdapter(chatAdapter);
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                chatmethod();
                handler.postDelayed(this, APP_REFRESH_TIME_IN_SEC * 1000);
            }
        }, APP_REFRESH_TIME_IN_SEC * 1000);

    }

    private void chatmethod() {
        chatdata.clear();
        String receiverid = getIntent().getStringExtra("ReceiverID");
        String chaturl = Constant.URL + "chathome.php?sid=" + Session.getUserID(getApplicationContext()) + "&rid=" + receiverid;
        Display.displaylog("Chat", chaturl);
        JsonObjectRequest chatreq = new JsonObjectRequest(Request.Method.GET, chaturl, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray chatsarray = response.getJSONArray("chats");
                    for (int i = 0; i < chatsarray.length(); i++) {
                        JSONObject chatobj = chatsarray.getJSONObject(i);
                        CBData cbchat = new CBData();
                        cbchat.setOwerid(chatobj.getString("sender_id"));
                        cbchat.setChatmessage(chatobj.getString("message"));
                        chatdata.add(cbchat);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                chatAdapter.notifyDataSetChanged();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Display.displaylog("ChatError", String.valueOf(error));
            }
        });
        chatreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(chatreq);
    }
}

ChatAdapter.java

    public class ChatAdapter extends BaseAdapter {
    List<CBData> chatlist;
    Context chatcontext;
    LayoutInflater chatinflater;

    public ChatAdapter(Context chatcontext, List<CBData> chatlist) {
        this.chatcontext = chatcontext;
        this.chatlist = chatlist;
    }

    @Override
    public int getCount() {
        return chatlist.size();
    }

    @Override
    public Object getItem(int position) {
        return chatlist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        chatinflater = (LayoutInflater) chatcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Chatholder chatholder;
        final CBData chatdatalist = chatlist.get(position);
        String owerid = Session.getUserID(chatcontext);
        if (convertView == null) {
            chatholder=new Chatholder();
            final boolean isMe = chatdatalist.getOwerid().equals(owerid);
            if (isMe) {
                convertView = chatinflater.inflate(R.layout.chatright, parent, false);
                chatholder.chatbubble = (TextView) convertView.findViewById(R.id.chatbubble);
                convertView.setTag(chatholder);
            } else {
                convertView = chatinflater.inflate(R.layout.chatleft, parent, false);
                chatholder.chatbubble = (TextView) convertView.findViewById(R.id.chatbubble);
                convertView.setTag(chatholder);
            }
        }else {
            chatholder= (Chatholder) convertView.getTag();
        }
        chatholder.chatbubble.setText(chatdatalist.getChatmessage());
//        TextView chatbubble = (TextView) convertView.findViewById(R.id.chatbubble);

        return convertView;
    }

    static class Chatholder {
        TextView chatbubble;
    }
}

更新了Message.java

public class Messages extends Activity {
    ListView chatview;
    ChatAdapter chatAdapter;
    List<CBData> chatdata;
    public int APP_REFRESH_TIME_IN_SEC = 1;
    Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_details);
        chatview = (ListView) findViewById(R.id.chatview);
        chatdata = new ArrayList<CBData>();
        chatAdapter = new ChatAdapter(getApplicationContext(), chatdata);
        chatview.setAdapter(chatAdapter);
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                chatmethod();
                handler.postDelayed(this, APP_REFRESH_TIME_IN_SEC * 1000);
            }
        }, APP_REFRESH_TIME_IN_SEC * 1000);

    }

    private void chatmethod() {
        chatdata = new ArrayList<CBData>();
        String receiverid = getIntent().getStringExtra("ReceiverID");
        String chaturl = Constant.URL + "chathome.php?sid=" + Session.getUserID(getApplicationContext()) + "&rid=" + receiverid;
        Display.displaylog("Chat", chaturl);
        JsonObjectRequest chatreq = new JsonObjectRequest(Request.Method.GET, chaturl, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray chatsarray = response.getJSONArray("chats");
                    for (int i = 0; i < chatsarray.length(); i++) {
                        JSONObject chatobj = chatsarray.getJSONObject(i);
                        CBData cbchat = new CBData();
                        cbchat.setOwerid(chatobj.getString("sender_id"));
                        cbchat.setChatmessage(chatobj.getString("message"));
                        chatdata.add(cbchat);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                chatAdapter = new ChatAdapter(getApplicationContext(), chatdata); 
                chatview.setAdapter(chatAdapter);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Display.displaylog("ChatError", String.valueOf(error));
            }
        });
        chatreq.setRetryPolicy(new DefaultRetryPolicy(500000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        AppController.getInstance().addToRequestQueue(chatreq);
    }
}

ChatDetail.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@color/colorPrimary"
        android:dividerHeight="2dp"
        android:id="@+id/chatview" />
</LinearLayout>

ChatLeft.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/chatbubble"
        android:gravity="left"
        android:textColor="#000"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:background="@drawable/chat_bg"
        />
</RelativeLayout>

ChatRight.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/chatbubble"
        android:layout_gravity="right"
        android:textColor="#000"
        android:padding="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:background="@drawable/chat_bg"
        />
</LinearLayout>

2 个答案:

答案 0 :(得分:0)

尝试使用

 ((BaseAdapter) chatview.getAdapter()).notifyDataSetChanged(); 

答案 1 :(得分:0)

在ChatAdapter内部添加以下代码

public void reload(List<CBData> chatlist) {
        this.chatlist=chatlist;
        notifyDataSetChanged();
    }

chatdata.clear();替换为chatdata = new ArrayList<CBData>();

chatAdapter.notifyDataSetChanged();替换为

chatAdapter.reload(chatdata);