java - 如何在Android中的聊天应用程序中更新新消息的 ListView

标签 java android listview android-listview scroll

我使用 ListView 来显示聊天,因为我使用 asynctask 从数据库中检索消息,然后使用适配器和数组列表将消息填充到项目中。然后如何更新每条新消息的 ListView 以及如何维护滚动位置以及如何在 android 中的标题中显示新消息的通知。

这是我的聊天 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;
        }

    }

请帮助我如何仅在数据库中到达每条新消息时更新 ListView 。

最佳答案

您需要在 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]));
            }
        } 

然后

@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);
    }

有可用的源代码 Simple Android Instant Messaging Application.

关于java - 如何在Android中的聊天应用程序中更新新消息的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19373179/

相关文章:

java - 我们可以在 Java 中捕获错误吗?

android - 选定选项卡下划线的 TabLayout 颜色

java - Listview 和 OnItemClickListener(蓝牙设备)

android - 单击按钮时在同一父 View 中多次膨胀 View

c# - 将项目添加到 WPF ListView 中的列

c# - 是否有与 C# 分区程序等效的 Java

java - 用Java生成图标图像

java - 弹出组合框并使用键盘快捷键选择

android - Xamarin.Forms 中未调用 OnOptionsItemSelected

java - 数据绑定(bind)和 Google 服务插件无法协同工作