Issue
I need a function to get all data/notes from FirebaseFirestore. How do I make this function wait for all data before return?
I think this function I created is not working in the main thread and return before getting data from firebase
public static ArrayList<NoteFB> getNotes() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
final String TAG = "FB Adapter";
final ArrayList<NoteFB> doFBs = new ArrayList<>();
db.collection("notesItem")
.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());
doFBs.add(document.toObject(NoteFB.class));
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
return doFBs;
}
MyFBAdapter myFBAdapter = new MyFBAdapter(ShowActivity.this, FBAdapter.getNotes());
rvContacts.setAdapter(myFBAdapter);
This code returns an empty ArrayList that creates an empty recyclerview.
Solution
Lots of these questions popping up lately. I had found the solution a while back : Using the Tasks API.
public static ArrayList<NoteFB> getNotes() {
FirebaseFirestore db = FirebaseFirestore.getInstance();
final String TAG = "FB Adapter";
final ArrayList<NoteFB> doFBs = new ArrayList<>();
try {
Task<QuerySnapshot> taskResult = Tasks.await(db.collection("notesItem").get(), 2, TimeUnit.SECONDS)
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
doFBs.add(document.toObject(NoteFB.class));
}
} catch(Exception e) {
Log.w(TAG, "Error getting documents.", e.localizedString());
}
return doFBs
}
Forgive me if I made any syntax errors my Java is a little rusty.
Make sure you are calling this code OFF the main thread, otherwise it will crash.
Answered By - Sean Blahovici
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.