Hello. Such a problem. There is an ArrayList () in which the current text messages are stored. The list displays the adapter.

Question: How to add data to ArrayList by clicking on a button?

@Override public void response(ArrayList<ResponseMsgArray> response) { // тут мои текущие данные int count = response.size() - 1; if(count > 0) { getEndMsgId = response.get(count).getNewMsg(); } if(sAdapter == null) { sAdapter = new ChatMsgAdapter(this, response); listView.setAdapter(sAdapter); Log.d(LOG_TAG, "Array:: setAdapter" + getEndMsgId); } else { sAdapter.setData(response); Log.d(LOG_TAG, "Array:: setData" + getEndMsgId); } } public void sendMsg(View v) { //кнопка editText = (EditText) findViewById(R.id.form_input); String form_input_msg = editText.getText().toString(); if (!form_input_msg.equals("")) { GetMsg getMsg = new GetMsg(); getMsg.SendMsg(getApplicationContext(), GET_ID, form_input_msg); } } 
  • How does your code relate to the question? Where is the attempt to add data? Most likely you just need to get a link to the List in the adapter and add the data using the addAll () method - YuriySPb
  • Well, I want to ask you how to do it right? I need to add data already to the existing list - sergei1094

1 answer 1

  1. Create an addData(List<ResponseMsgArray> dataToAdd) method in the adapter addData(List<ResponseMsgArray> dataToAdd)
  2. In it, use the method of adding data to the list innerAdapterData.addAll(dataToAdd);
  3. Immediately after calling this method, notify the adapter about changes in it using the notifyDataSetChanged() method
  • I already have a setData method in the adapter. In general, the essence is this, I send messages to the server, and when I press the "send" button, I want the text to be entered immediately displayed in the adapter - sergei1094
  • @ sergei1094, this method of yours can be done in different ways. You either clean the existing list and add new data using the addAll method or assign a variable a reference to the new list. These methods are very different. If you need to add only one element to the list, then replace the list with one variable in the method and add it via add() - Juriy Spb
  • one
    I understood your direction. I understood everything and I think I can handle it. Thank you - sergei1094