How to display the user data in navigation header from firestore database in android studio

Viewed 134

I want to display the user data in navigation header from firestore database. I have tried this code but not use

   firebaseDatabase.getReference().child("users").child(auth.getUid())
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    //we have Users class which contain user properties and methods.
                    User user = snapshot.getValue(User.class);

                    View header = navigationView.getHeaderView(0);

                    name = header.findViewById(R.id.your_name);
                    username = header.findViewById(R.id.user_name);


                    name.setText(user.getName1());
                    username.setText("@" + user.getUsername1());
                }

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

                }
            });

enter image description here

2 Answers

You question and tags say you want to use Firestore, but in your code you access the Realtime Database. Both databases are part of Firebase, but they are completely separate and the API from one can't be used access data from the other.

If you want to read data from Firestore, I recommend starting with the documentation on that.

In my question, I had used Realtime Database and this is how I needed it. Displaying the data from Firestore Database in the navigation header.

 NavigationView navigationView = findViewById(R.id.nav_view);

 DocumentReference documentReference = database.collection("users").document(userId);
    documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
        @Override
        public void onEvent(DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException error) {

            View header = navigationView.getHeaderView(0);

            name = header.findViewById(R.id.your_name);
            username = header.findViewById(R.id.user_name);

            name.setText(snapshot.getString("name1"));
            username.setText(snapshot.getString("username1"));

        }
    });
Related