Get Specific Field from Firestore with whereEqualTo - android

I have a firebase document and i want to extract fields values to TextView in adnroid where the currentuser id from mAuth equals the user-id field inside the document but it's not working
Firebase Document Image
db = FirebaseFirestore.getInstance();
db.collection("users")
.whereEqualTo("user-uid",uid)
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
user_name = task.getResult().getString("user-name");
user_email = task.getResult().getString("user-email");
user_last_name = task.getResult().getString("user-last-name");
user_phone_number = task.getResult().getString("user-phone-number");
}
});

db.collection("users")
.whereEqualTo("user-uid",uid)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
Toast.makeText(getActivity(),"success accessing database",Toast.LENGTH_SHORT).show();
for (QueryDocumentSnapshot document : task.getResult()){
//Fetch from database as Map
user_name = (String) document.getData().get("user-name");
user_last_name =(String) document.getData().get("user-last-name");
user_phone_number =(String) document.getData().get("user-phone-number");
user_email =(String) document.getData().get("user-email");

Related

How to iterate a Firestore collection on 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());
}
}
});

How can I retrieve all the collection data users saved from Firebase Database using android studio?

I want to retrieve and show Collection data saved in Firebase database on the android screen.
I get three types of information(orders, quantity, date) from the users and save them on the database using :
OrderInfo orderInfo = new OrderInfo(orderText, quantityText, dateText);
db.collection("orders").document(user.getUid()).set(orderInfo)
And now I want to retrieve all the data(orderText, quantityText, dateText)
saved in collection "orders" maybe in the form of list.
How can I do that?
To get the values of your orderText, quantityText and dateText properties within a single OrderInfo object, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
ordersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
OrderInfo orderInfo = document.toObject(OrderInfo.class);
Log.d(TAG, orderInfo.getOrderText() + " / " + orderInfo.getQuantityText() + " / " + orderInfo.getDateText());
}
}
}
});
If you want to get all OrderInfo objects within your orders collection, please use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference ordersRef = rootRef.collection("orders");
ordersRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<OrderInfo> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
OrderInfo orderInfo = document.toObject(OrderInfo.class);
list.add(orderInfo);
}
//Do what you need to do with your list
}
}
});

how to get auto generate id of a document in cloud firestore?

I want to get auto generated id of a document
how can i getting these auto generated id's?
https://i.stack.imgur.com/tgui0.png
You can achieve this by using DataReference.push() method of DataReference object.
You can see here for more info.
you can try this :-
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("MartWayDB")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String id = document.getId();
//or you can store these id in array list
}
} else {
Toast.makeText(MainActivity.this, "Error getting documents."+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
or you can follow this link :
https://firebase.google.com/docs/firestore/quickstart?authuser=0

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()...

How to get a count of the number of documents and the id's of these, in a collection with Cloud Firestore

In Firestore, how can I get the total number of documents and the id's of these in a collection?
For instance if I have
/Usuarios
/Cliente
/JORGE
/456789
/filtros
/status
/activo
/inactivo
My code:
FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<QuerySnapshot> docRef = db.collection("Usuarios").document("Cliente").collection("JORGE").document("filtros").collection("status").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
int contador = 0;
for (DocumentSnapshot document: task.getResult()) {
contador++;
}
int cantPS = contador;
}
I want to query how many people I have and get: 2 and the id's: activo, inactivo.
To determine the number of documents returned by a query, use QuerySnapshot.size().
To get the list of documents returned by a query, use QuerySnapshot.getDocuments().
To show the key of a document use DocumentSnapshot.getId().
So in total:
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
QuerySnapshot querySnapshot = task.getResult();
int count = querySnapshot.size();
System.out.println(count);
for (DocumentSnapshot document: querySnapshot.getDocuments()) {
System.out.println(document.getId());
}
}
}

Categories

Resources