How to iterate a Firestore collection on Android? - android

I have a Firestore collection like this:
Take a look at kost collection. There are 4 docouments in it, and each document has the following fields: fasilitas, gender, harga, etc
For each document, I want to retrieve all the fields.
Now I have this:
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
for (DocumentSnapshot ds:task.getResult()){
}
}
}
});
It's not even a correct code, task.getResult() is underlined:
foreach not applicable to type
'com.google.firebase.firestore.DocumentSnapshot
What's the correct way, then?

Your problems is in this code:
DocumentReference docRef = firestore.collection("kost").document();
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
Your docRef points to a new, empty document. What you want instead is to point to the entire collection as shown in the documentation on reading all documents in a collection:
db.collection("kost")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

Related

Get array from Firestore Kotlin [duplicate]

I am using Cloud Firestore and there is a array data in field. So how can I get data from array individually?
To get the values within ip_range array, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("aic").document("ceo").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("ip_range")) {
Log.d("TAG", entry.getValue().toString());
}
}
}
}
}
});
Another approach would be:
rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
Log.d(TAG, list.toString());
}
}
}
});
In both cases, the output in your logcat will be:
[172.16.11.1, 172.16.11.2]

Android Firestore get field values by document id

I have a Firebase Firestore database in which I have to get all the field's inside a document by document id.
How to get the all the field values (inside Green Box) by document id (Red box)
If you want to get that specific document you can try this
DocumentReference docRef = db.collection("projects").document("YOURDOCIDHERE");
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());
}
}
});
If you want get all documents by key order then you can try making a query like this.
docRef.orderByKey()
Check firebase documention for more info.

How to fetch data just one time from firebase and don't listen to any data change

I'm new to firebase and recently started working on this. Every tutorial I saw, is about how to listen to data change in cloud firestore. What if I want to fetch teh data just once and don't wanna set anyy listener on them. Example scenario is, just fetching the data user last login time or profile data of any user
The documentation has a dedicated section about getting data a single time for a query. Just use the get() method on the query you build:
db.collection("cities")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
Or, for a single document:
DocumentReference docRef = db.collection("cities").document("SF");
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());
}
}
});

How to get all field and immediately assign it?

How i can get all the field and immediately assign it to some variable
I tried this
db= FirebaseFirestore.getInstance();
db.collection("Users")
.whereEqualTo("email", email)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
}
});
I dont know if it the correct way and i dont know how to complete it.
I think it will easy for you to use Firestore.
With Firestore you can easily get the records with like "where" conditions.
Please check this example mentioned in the Firestore documentation (https://firebase.google.com/docs/firestore/query-data/get-data).
db.collection("cities")
.whereEqualTo("capital", true)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});

How to fetch sub-collection data from firestore

I have a collection called TripInfo following with user's id and then I have created subcollection with auto generate id for each doc. The problem is I can't fetch the data using the following code:
private void checkDataExistingDate() {
db.collection("TripsInfo").document(UID).collection("Individual_Trip").document()
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.getResult().exists()){
DocumentSnapshot snapshot = task.getResult();
Map<String, Object> map = snapshot.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
Log.d(Tag, "All data"+entry.getValue().toString());
}
}
}
});
Or do I need to store the without subcollection? In Realtime we were using push to generate auto-id, but here I don't know what is the equivalent to create a key after placing the user's id in the document.
Suppose you have store userid with uid parameter in TripsInfo collection and also have Individual_Trip as subcollection in 'TripsInfo' collection. you can fetch subcollection like this.
FirebaseFirestore.getInstance().collection("TripsInfo")
.get()
.addOnCompleteListener(
new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (FirebaseAuth.getInstance().getUid().equalsIgnoreCase(document.getString("uid"))) {
document.getReference()
.collection("Individual_Trip")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
list = task.getResult().toObjects(Individual_Trip.class);
showListOfRequest();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
hideProgress();
}
});
break;
}
}
}
}
});
FirebaseAuth.getInstance().getUid().equalsIgnoreCase(document.getString("uid"))
this line is for checking for userid, when you have multiple data in your 'TripsInfo' collection.
you can also use whereEqualTo for that, FirebaseFirestore.getInstance().collection("TripsInfo")
.whereEqualTo("userId", "uid").get()...

Categories

Resources