How to display message from firebase to TextView Android Studio?

Viewed 654

I want to know how to display this "Hello, World" message from my database to one of my TextViews? Thank you.

enter image description here

1 Answers

If you want to show the value from the Firebase Realtime Database, there 3 ways. But I will show you the simple way.

I continue with your code.

TextView fireBaseTextView;
TextView fireBaseTextView2;

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

    fireBaseTextView = findViewById(R.id.fireBaseTextView);
    fireBaseTextView2 = findViewById(R.id.fireBaseTextView2);

    //Write a message to the database
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    final DatabaseReference myRef = database.getReference("message");

    myRef.setValue("Hello, World");

    //Display the message from the database
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                final String message = dataSnapshot.getValue(String.class);
                fireBaseTextView2.setText(message);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}
Related