简体   繁体   English

如何为聊天应用程序在android中更新新消息的listview

[英]how to update the listview for the new message in android for the chat application

i'm using the listview for the showing the chat, in that i used asynctask to retrieve the message from the database and then i populate the message in the item using adapter and arraylist. 我使用列表视图来显示聊天,因为我使用asynctask从数据库中检索消息,然后使用适配器和arraylist在项目中填充消息。 then how to update the listview for the every new message and how to maintain the scroll position and how to show the notification for the new message in the title in android. 然后如何为每条新消息更新listview以及如何保持滚动位置以及如何在android标题中显示新消息的通知。

this is my chat activity 这是我的聊天活动

 public class ChatActivity extends Activity implements OnScrollListener {
        ListView listview;

        MessageTask task;
        Handler handler;
        ArrayList<String> tExp=new ArrayList<String>();
        Boolean loadingMore = true;
        List list = new ArrayList();
        Boolean stopLoadingData = false;

        EditText edit;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_chat);

             txt=(TextView)findViewById(R.id.roomname);
            listview =(ListView)findViewById(R.id.messagelist);
             edit=(EditText)findViewById(R.id.editText1);

             txt.setText(message);

             task = new MessageTask();
             task.execute(new String[]{URL});


        }



     class MessageTask extends AsyncTask<String, Void, List<String>> {

             private final HttpClient Client = new DefaultHttpClient();

            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @Override
            protected List<String> doInBackground(String... params) {

                String output = "";
               for(String out:params){

                     try{
                     HttpGet httpget = new HttpGet(out);
                     ResponseHandler<String> responseHandler = new BasicResponseHandler();
                     output = Client.execute(httpget, responseHandler);

                       try {


                        JSONObject jObject= new JSONObject(output);
                        JSONArray menuObject = new JSONArray(jObject.getString("response"));   

                        //HashMap<String,ArrayList> map = new HashMap<String,ArrayList>();

                      for (int i = 0; i<menuObject.length(); i++)
                      {

                         list.add(menuObject.getJSONObject(i).getString("fk_username_c").toString()+" "+menuObject.getJSONObject(i).getString("message_c").toString());     

                     }
                      adapter=new ArrayAdapter<String>(ChatActivity.this,android.R.layout.simple_list_item_1);

                       } catch (JSONException e) {
                           Log.e("log_tag", "Error parsing data ");
                       }
                     }catch(Exception e){
                         Log.i("Animation", "Thread  exception " );
                     }
               }

              return list;

            }


    @Override      
    protected void onPostExecute(List<String> list) {


          adapter.notifyDataSetChanged();
          listview.setAdapter(adapter);
          adapter.clear();
         listview.clearTextFilter();
          adapter.addAll(list);
          loading=false;

     }
    }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.chat, menu);
            return true;
        }

    }

plz help me how to update the listview only for the every new message is arrived in the database. 请帮助我如何仅在数据库中收到每条新消息时更新listview。

You will need to update list content in onProgressUpdate method 您将需要在onProgressUpdate方法中更新列表内容

ArrayList<Message> messages;
@Override
        public void onProgressUpdate(String... v) {

            /*
             * check wether we have already added a status message
             */
            if (messages.get(messages.size() - 1).isStatusMessage) {
                /*
                 * update the status for that
                 */
                messages.get(messages.size() - 1).setMessage(v[0]);
                adapter.notifyDataSetChanged();
                getListView().setSelection(messages.size() - 1);
            } else {
                /*
                 * add new message, if there is no existing status message
                 */
                addNewMessage(new Message(true, v[0]));
            }
        } 

And Then 接着

@Override
        protected void onPostExecute(String text) {

            /*
             * check if there is any status message, now remove it.
             */
            if (messages.get(messages.size() - 1).isStatusMessage) {
                messages.remove(messages.size() - 1);
            }
            /*
             * add the orignal message from server.
             */
            addNewMessage(new Message(text, false));
        }

    }

    void addNewMessage(Message m) {
        messages.add(m);
        adapter.notifyDataSetChanged();
        getListView().setSelection(messages.size() - 1);
    }

There is a source code available Simple Android Instant Messaging Application. 有可用的源代码, 简单Android即时消息应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM