How to use Firebase Cloud Firestore references with clean code? - android

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");
}
}

Related

Firestore RecyclerView - Variable null

When I save the value that it retrieves from firestore when exiting the function, this value is null.
#Override
protected void onBindViewHolder(#NonNull ViewDonationHolder holder, int position, #NonNull DonationsClass model) {
beneficiaryUID = model.getBeneficiaryUid();
DocumentReference docRef = db.collection("beneficiaries").document(beneficiaryUID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
beneficiaryFirstName = document.getString("firstName");
beneficiaryLastName = document.getString("lastName");
Log.e("fullName", fullNameBeneficiary);
} else {
}
} else {
}
fullNameBeneficiary = beneficiaryFirstName + " - " + beneficiaryLastName;
}
});
holder.txtFullname.setText(fullNameBeneficiary);
holder.txtDate.setText(model.getDate());
holder.txtType.setText(model.getType());
holder.txtQuantity.setText(model.getQuantity());
holder.txtDescription.setText(model.getDescription());
}
When holder.txtFullname.setText(fullNameBeneficiary) in interface is empty
Have you tried like this -
DocumentReference docRef = db.collection("beneficiaries").document(beneficiaryUID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
beneficiaryFirstName = document.getString("firstName");
beneficiaryLastName = document.getString("lastName");
fullNameBeneficiary = beneficiaryFirstName + " - " + beneficiaryLastName;
Log.e("fullName", fullNameBeneficiary);
}
}
}
});

How to get size for Firestore POSTID Collection in Android? [duplicate]

This question already has answers here:
How to count the number of documents under a collection in Firestore?
(3 answers)
Closed 2 years ago.
See the code:
private void initFirebase() {
try {
for (int i = 1; i < 16; i++) {
mDatabase.collection(POST_ID).document("1").collection(PREVIEW)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
postMap.putAll(document.getData());
}
if (postMap != null) {
Post post = new Post();
post.setTitle(Objects.requireNonNull(postMap.get(POST_NAME)).toString());
post.setDesc(Objects.requireNonNull(postMap.get(POST_DESC)).toString());
post.setUrl(Objects.requireNonNull(postMap.get(POST_URL)).toString());
postList.add(post);
}
setAdapter();
} else {
showLog("Error getting documents: " + task.getException());
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
instead of for (int i = 1; i < 16; i++) { 16 I want the size which existed in my Firestore Collection. I tried all suggestion, but there is no mDatabase.collection(POST_ID).size()
DB Structure:
Firestore-root
|
--- PostId (collecton)
|
---
I want the size of postId collection.
For size
int count = 0;
db.collection("POST_ID")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
count = task.getResult().size();
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
private void initFirebase() {
try {
for (int i = 0; i < count; i++) {
mDatabase.collection(POST_ID).document(i).collection(PREVIEW)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
postMap.putAll(document.getData());
}
if (postMap != null) {
Post post = new Post();
post.setTitle(Objects.requireNonNull(postMap.get(POST_NAME)).toString());
post.setDesc(Objects.requireNonNull(postMap.get(POST_DESC)).toString());
post.setUrl(Objects.requireNonNull(postMap.get(POST_URL)).toString());
postList.add(post);
}
setAdapter();
} else {
showLog("Error getting documents: " + task.getException());
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
Then use this count variable as size.

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 root document fields of collection in firestore 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

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