0

I am developing a realtime messaging application. I have gotten as far as the user messages being stored in Firebase Realtime Database. But not able to populate them back into a listview. I have a method called displayMessages() where I want to pull all the messages back from the Database and populate into a ListView. For some reason It is not populating the View and I am not sure why. Anyone able to help.

public class ChatRoom extends AppCompatActivity {
    private FirebaseAuth mAuth;
    private EditText input;
    private FloatingActionButton fab;
    private FirebaseListAdapter<Comment> adapter;
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_room);
        fab = findViewById(R.id.fab);
        input = findViewById(R.id.input);
        mAuth = FirebaseAuth.getInstance();
        final String userID = mAuth.getUid();
        assert userID != null;
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                User user = snapshot.getValue(User.class);
                assert user != null;
                String userName = user.getUserName();
                createMessage(userName);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
            }
        });
        displayMessages();
    }


    public void createMessage(final String userName) {
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (input.getText().toString().isEmpty()) {
                    Toast.makeText(ChatRoom.this, "Message is empty!", Toast.LENGTH_SHORT).show();
                } else {
                    Date date = new Date();
                    String currentDateTime = dateFormat.format(date);
                    mAuth = FirebaseAuth.getInstance();
                    final String userID = mAuth.getUid();
                    Comment comment = new Comment(input.getText().toString(), userName,userID,currentDateTime);
                    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
                    databaseReference.child("Chat").push().setValue(comment).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if (task.isSuccessful()) {
                                Toast.makeText(ChatRoom.this, "Message Saved", Toast.LENGTH_SHORT).show();
                                input.setText("");
                                displayMessages();
                            }
                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(ChatRoom.this, "Error Occurred: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    //I am able to write new messages to firebase realtime database
    //I need to fix this method and populate the list with the messages from the database
    public void displayMessages() {
        Query query = FirebaseDatabase.getInstance().getReference().child("Chat");
        ListView listOfMessages = findViewById(R.id.list_of_messages);
        FirebaseListOptions<Comment> options =
                new FirebaseListOptions.Builder<Comment>()
                        .setQuery(query, Comment.class)
                        .setLayout(R.layout.message)
                        .build();
        adapter = new FirebaseListAdapter<Comment>(options){
            @Override
            protected void populateView(@NotNull View v, @NotNull Comment model, int position) {
                TextView messageText = v.findViewById(R.id.message_text);
                TextView messageUser = v.findViewById(R.id.message_user);
                TextView messageTime = v.findViewById(R.id.message_time);
                messageText.setText(model.getMessageText());
                messageUser.setText(model.getMessageUser());
                messageTime.setText(model.getDateTime());
            }
        };
        listOfMessages.setAdapter(adapter);
    }
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
ajai singh
  • 33
  • 7
  • This link may help: https://stackoverflow.com/questions/46912532/android-using-firebaseui-with-firebaselistoptions-to-populate-a-listview-doesnt – i_A_mok Nov 18 '20 at 07:24
  • I was able to fix my code with that link earlier on thanks anyways :) – ajai singh Nov 18 '20 at 12:12

0 Answers0