kartik
kartik

Reputation: 139

How to fetch or get data from Cloud Firestore Firebase in android

I am using this code:

DocumentReference docRef = db.collection("Users").document("user_01");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null && document.exists()) {

            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

But I don't know how to get. I know with the help of put() I able to insert data on Cloud Firestore, but I don't know how to fetch data which is placed in user_01.

Upvotes: 1

Views: 4753

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Assuming you have a property caled name under each user object, to solve this, please use the following code:

DocumentReference docRef = db.collection("Users").document("user_01");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null && document.exists()) {
                Log.d("TAG", document.getString("name")); //Print the name
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

Upvotes: 6

Related Questions