I have this function to return number of nodes at a firestore endpoint but it seems not to ork as expected. Currently, the number of nodes at the endpoint is 1.Here is the function
public static int getInvoicesCount(String uid)
{
final int[] count = new int[1];
FirebaseFirestore firestore;
firestore = FirebaseFirestore.getInstance();
CollectionReference invoicesRef = firestore
.collection("invoices");
Query query = invoicesRef.whereEqualTo("creator_id",uid);
Task<QuerySnapshot> task = query.get();
task.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
if(task.getResult().isEmpty())
{
count[0] = 0;
Log.d("counter",String.valueOf(count[0]));
}
else {
Log.d("counter is",String.valueOf(task.getResult().size()));
count[0] = task.getResult().size();
}
}
}
});
return count[0];
}
Logging the value of count[0] in the else statement gives 1 but the return value at the end of the function is still giving 0 instead of 1;
The code you have in onComplete
method is invoked a lot after your method is returning, when your task is completed. In your code you are just attaching the listener, it can be called a lot later or even never at all.
You have a lot of options, for example Future , or attaching a callback to your listener (so listener calls the callback after it completes).
task.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful())
{
if(task.getResult().isEmpty())
{
count[0] = 0;
Log.d("counter",String.valueOf(count[0]));
}
else {
Log.d("counter is",String.valueOf(task.getResult().size()));
count[0] = task.getResult().size();
}
methodWhenListenerCompletes(count[0]);
}
}
});
...
public void methodWhenListenerCompletes(int count) {
// do something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.