how to get root document fields of collection in firestore android - android

I want to get the document fields of the root collection in android firestore
my database structure in firestore is
collection
documents-->root fields
collection
documents-->fields
now i want to get root fields. How to do that in android firestore?
firestore.collection("Players").orderBy("deptName").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//model class
Example example=document.toObject(Example.class);
exampleList.add(example);
}
Toast.makeText(getActivity(), ""+exampleList, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), ""+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});

use this line document.getId();
firestore.collection("Players").orderBy("deptName").get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//model class
Example example=document.toObject(Example.class);
example.setDocID(document.getId());
exampleList.add(example);
}
Toast.makeText(getActivity(), ""+exampleList, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), ""+task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
https://firebase.google.com/docs/firestore/query-data/get-data#java_2

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 to use Firebase Cloud Firestore references with clean code?

So, I'm using Firebase Cloud and I have three references that I go through until I get my data.
this issue made me create 3 anonymous nested classes- which looks horrible, hard to follow and probably hard code to maintain.
I've added that code, I hope for your advice - how should I clean it up?
db.collection("users").document(mAuth.getUid())
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
Thanks in advance!
you can try something like this :
db.collection("users").document(mAuth.getUid())
.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
callback1(document);
} else {
Log.d(TAG, "No such document as userproj");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
private void callback1(DocumentSnapshot document)
{
((DocumentReference)document.get("Users_Project")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback2();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void callback2(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
((DocumentReference) document.get("Project_Schedule")).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
callback3();
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
} else {
Log.d(TAG, "No such document as projectschedule");
}
}
private void callback3(DocumentSnapshot document)
{
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//we got the data!!!!
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
Log.d(TAG, "No such document as projectschedule ref");
}
}

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 firestore document list in real time android

i want to get the firebase document list in real time when a change occur for android
here is my code
firestore.collection("Players").orderBy("deptName").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
documentList.add(document.getId());
}
Firestore's documentation gives good examples on how to read/write from it. You can find full Docs here
For your specific need you can head to : Listen to multiple documents in a collection
Here is the code :
db.collection("Players")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
for (QueryDocumentSnapshot doc : value) {
documentList.add(doc.getId());
}
}
});

How to search from the cloud-firestore database?

I want users to type their email and password. After Authentication, based on their email I want to check whether they are admin or not and open different activities thereafter. How should I perform the search query? Is it even possible?
Below is the answer which worked for me. For general see Alex answer.
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
rootRef.collection("Users").whereEqualTo("Email","ashish#gmail.com").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.getString("Admin").equals("Yes")) {
Toast.makeText(Login.this, "Logged In!", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(Login.this, MainActivity.class));
} else {
Toast.makeText(Login.this, "Logged In!", Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(Login.this, nonadmin.class));
}
}
} else {
mProgressBar.setVisibility(View.GONE);
Toast.makeText(Login.this, "Sign In Problem", Toast.LENGTH_LONG).show();
}
}
});
}
}
});
To solve this, please use the following code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
rootRef.collection("Users").whereEqualTo("Email", "ashish#startup.com").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
if (document.getString("Admin").equals("Yes")) {
Log.d(TAG, "User is Admin!");
}
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
The output will be: User is Admin!.
Don't also forget to set your security rules like this:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}

Categories

Resources