如何在我的代码上实现notifyDataSetChanged()?

时间:2015-06-15 22:48:39

标签: android

我构建了一个Chat,它从Json文件中获取所有数据,

我遇到的问题是,当有人发送消息时,聊天需要自动更新。我搜索了很多关于我的问题,我发现有可能做我正在尝试调用notifyDataSetChanged。

我尝试在我的代码上实现它,但我无法得到任何结果,你能帮助我吗?

我的代码(我删除了一些不必要的变量):

public class ChatRoomActivity extends ListActivity {

    // contacts JSONArray
    JSONArray contacts = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatroom); 

        String userimage = intent.getStringExtra("image");

        send = (ImageButton) findViewById( R.id.send );
        txtmessage = (EditText) findViewById( R.id.txtmessage );
        userphoto = (ImageButton) findViewById( R.id.userphoto );

        contactList = new ArrayList<HashMap<String, String>>();
        lv = getListView();

        call();

    }

    private void call() {

         task = new GetContacts();
         task.execute(id);

    }


    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Showing progress dialog


            pDialog = new ProgressDialog(ChatRoomActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.hide();

        }

        protected Void doInBackground(String... arg0) {


            String getinfo = (String)arg0[0];
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url + "&id=" + id, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);


                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {


                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String userid = c.getString(TAG_USERID);
                        String userone = c.getString(TAG_USERONE);
                        String usertwo = c.getString(TAG_USERTWO);
                        String message = c.getString(TAG_MESSAGE);
                        String pic_url_get = c.getString(TAG_IMAGE);
                        String conversation_id = c.getString(TAG_CONVERSATION);

                        String position = ""; 

                        if (username.equals(userid)) {
                            position = "right";
                        }else{
                            position = "left"; 
                        } 

                         contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, id); 

                        contact.put(TAG_MESSAGE, message);
                        contact.put(TAG_POSITION, position);
                        contact.put(TAG_CONVERSATION, conversation_id);
                        contact.put(TAG_USERONE, userone);
                        contact.put(TAG_USERTWO, usertwo);
                        contact.put(TAG_IMAGE, "http://www.website.com/images/" + userid + "/" + pic_url_get);    

                        // adding contact to contact list
                        contactList.add(contact);

                        if(isCancelled())
                            break;   

                    }

                } catch (JSONException e) {
                    e.printStackTrace(); 
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);


            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */

            adapter =  new costumeadapter(
                            ChatRoomActivity.this,
                            contactList,
                            R.layout.chat_row,
                            new String[]{ TAG_MESSAGE, TAG_CONVERSATION },
                            new int[]{ R.id.name, R.id.conversationid });

            setListAdapter(adapter);
        }

    }


    public class costumeadapter extends SimpleAdapter{ 

        public costumeadapter(ChatRoomActivity chatRoomActivity,
                    ArrayList<HashMap<String, String>> contactList, int listItem,
                    String[] strings, int[] is) {
            super(chatRoomActivity, contactList, listItem, strings, is);
                // TODO Auto-generated constructor stub
            } 


        public View getView(int position, View convertView, ViewGroup parent){

              View v = super.getView(position, convertView, parent);


              TextView text = (TextView) v.getTag();
              RelativeLayout lay = (RelativeLayout) v.findViewById(R.id.layout);

              if(text == null){
                 text = (TextView) v.findViewById(R.id.name);
                  v.setTag(text);
              } 

             String url = (String) ((Map)getItem(position)).get(TAG_POSITION);

             String userone = (String) ((Map)getItem(position)).get(TAG_USERONE);
             String usertwo = (String) ((Map)getItem(position)).get(TAG_USERTWO);

             text.setBackgroundResource(url.equals("left") ? R.drawable.bubble_yellow : R.drawable.bubble_green);
             lay.setGravity(url.equals("left") ? Gravity.LEFT : Gravity.RIGHT);
             conversationid = (TextView)v.findViewById(R.id.conversationid);

             if(userone.equals(username)){
                linkprofile = usertwo;
             }else{
                linkprofile = userone;
             }
             getconversationid = conversationid.getText().toString();

             send.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {

                    SendMessage mTask = new SendMessage();
                    mTask.execute(username,getmessage,getconversationid);

                 } 
             });  

              return v;  

           }
        }     
    }

2 个答案:

答案 0 :(得分:0)

您可以将以下代码放在方法onCreate()

adapter =  new costumeadapter(
                        ChatRoomActivity.this,
                        contactList,
                        R.layout.chat_row,
                        new String[]{ TAG_MESSAGE, TAG_CONVERSATION },
                        new int[]{ R.id.name, R.id.conversationid });

        setListAdapter(adapter);

在onPostExecute()中向contactList添加元素时添加调用adapter.notifyDataSetChanged() 注意:adapter应该是会员字段

答案 1 :(得分:0)

当您的适配器使用的数据集已更改时,应调用notifyDataSetChanged。从我在你的代码中可以看出,这是contactList。每当将新项目添加到contactList,并将contactList绑定到适配器时,您将调用adapter.notifyDataSetChanged并更新列表视图。我不确定你何时收到消息并不是很明显,但如果你有一个名为messageReceived的AsynTask,你可以在onPostExecute()方法中调用adapter.notifyDataSetChanged()。需要注意的是,需要在MainThread上调用onDataSetChanged。如果主线程调用AsyncTask而不是onPostExecute()方法将正常工作。否则你需要做类似

的事情
    ChatRoomActivity.this.runOnUiThread(
       new Runnable(){
          @Override public void run(){ 
          adapter.notifyDataSetChanged(); 
     }});
相关问题