androidandroid-recyclerviewchatroom

How to be able to save data in a list and show them in recyclerview


I'm new to android and I've been tinkering with recycler view in a chatroom and showing text from EditText to TextView in a bubble chat. So! I just want to show every single text that I write in edit text in text views BUT! I just can show one text at the time :( I save them in a list. is there a way for me to show all my text in text views? there is no User it just a one-way message. this is my onCreate on MainActivity.

Chat chat = new Chat();
List<Chat> chatList = new ArrayList<>();


imageButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view){
        String msg = editText.getText().toString();
        if(!msg.equals("")){
           chat.setMessage(msg);
           chatList.add(chat);
            detailAdaptor = new DetailAdaptor(DetailActivity.this,chatList);
            recyclerView.setAdapter(detailAdaptor);
        } else {
            Toast.makeText(DetailActivity.this ,
                    "Cant send empty message" , Toast.LENGTH_LONG);
        }
        editText.setText("");

also, I can show multiple messages but I have to declare my chat/List final and that makes all my messages the same.

My Chat class:

public class Chat {
    private String Message;

    public Chat(String message){
        Message = message;
    }

    public Chat(){
    }

    public String getMessage(){
        return Message;
    }

    public void setMessage(String message){
        Message = message;
    }
}

pic with final Variable

pic with the original problem


Solution

  • If I understand your question correctly, you want to show messages you type in the edit text and just want to show that in the recyclerview. I think this will help in achieving the thing you want to achieve.

    1. Initialize and set the adapter before the image button on click method (be it with empty list).

    2. Inside the on click listener add data to the list you passed to the adapter while initializing and call notifyItemSetChanged, something like

      adapter.notifyDataSetChanged()