Usman Shahid
Usman Shahid

Reputation: 25

How to retrieve data of current firestore user

This is my firestore database image I want to get data from the current firestore user. I am retrieving the data which is at the last of firestore list. I want the current user data.

This is my code of retrieving data.

firestore.collection("Teacher Database").get()
               .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                   @Override
                   public void onComplete(@NonNull Task<QuerySnapshot> task) {
                       if(task.isSuccessful()) {
                           for (DocumentSnapshot documentSnapshot : task.getResult()) {
                               String name = documentSnapshot.getString("Username");
                               String email = documentSnapshot.getString("Email");
                               String city = documentSnapshot.getString("City");
                               String skill = documentSnapshot.getString("Skills");

                               textView_nameTeacher.setText(name);
                               textView_emailTeacher.setText(email);
                               textView_cityTeacher.setText(city);
                               textView_skillTeacher.setText(skill);
                           }
                       }

                   }
               }).addOnFailureListener(new OnFailureListener() {
           @Override
           public void onFailure(@NonNull Exception e) {
               Toast.makeText(getContext(), "Error!", Toast.LENGTH_LONG).show();

           }
       });

Upvotes: 0

Views: 59

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80944

Since you are using firebase authentication, then do the following:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DocumentReference docRef = db.collection("Teacher Database").document(user.getUid());
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Log.d(TAG, "DocumentSnapshot data: " + document.getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

First, get the currently logged in user, and then pass the uid as an argument to the document()

Upvotes: 1

Related Questions