0

For example I have defined a custom object called Subject with fields (name- age...) and on firestore the documents have the same format (name -age..). To get document I use :

SubjectReference.document(document.getId()).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                    if (task.isSuccessful()) {
                                        DocumentSnapshot document = task.getResult();
                                        if (document != null) {
                                           Subjectt subjectt = task.getResult().toObject(Subjectt.class);
                                        } else {
                                            Log.i("selected", "No such document");
                                        }
                                    } else {
                                        Log.i("selected", "get failed with ", task.getException());
                                    }
                                }
                            });

What I want is I want to use this object from within the activity/fragment. However I cannot make the funtion return the object Subject. Is there any other way to do it?

Is it possible to get a document in firestore as custom object to use it in android activity?

  • If I understand your question correctly, then you can declare```final Subjectt subjectt = new Subjectt()``` outside the listener and then do```subjectt = task.getResult().toObject(Subjectt.class)``` inside onComplete(). – James Aug 25 '20 at 17:02
  • Sometimes I get null object if I do that. Say I run the method and just after the method I do Subject.getname(); I will get a null value because the listener isn't complete. @James – Naima Abiad Aug 26 '20 at 08:15
  • 1
    Well, it would be simpler if you could do whatever you wanted to do within the listener, but if you can't, then you will have to wait for the async call to complete before you use the object. This might help [link](https://stackoverflow.com/questions/56402128/wait-for-firestore-queries-to-complete) – James Aug 26 '20 at 08:48
  • The simple answer is no, you cannot do that. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a custom callback. – Alex Mamo Aug 28 '20 at 07:38

0 Answers0