3

When I run this method returns V = null, In consideration V inside onComplete(... , its not null

public static Vehicle v;

public static Vehicle tessst() {

    v = new Vehicle();

    DocumentReference docRef = db.collection("vehicles").document("123");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

            if(task.isSuccessful()){
               DocumentSnapshot documentSnapshot = task.getResult();
                if(documentSnapshot !=null){
                    v  = documentSnapshot.toObject(Vehicle.class);
                }
            }
        }
    });
      return  v;
}
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
isme
  • 57
  • 1
  • 7
  • Possible duplicate of [Firestore - object with inner Object](https://stackoverflow.com/questions/48499310/firestore-object-with-inner-object) – Alex Mamo Apr 08 '18 at 17:10
  • Please see the duplicate to see why your v object is null and how you can solve this using a custom callback. – Alex Mamo Apr 08 '18 at 17:34

1 Answers1

4

Firebase Firestore get() method fetches and returns the object asynchronously which means chronologically the following occurs:

  1. return v; statement would have executed first
  2. then get() fetches the document details and assigns to v = documentSnapshot.toObject(Vehicle.class);

So instead of returning object v using return v; from the method you should call a listener and set the object v after it is fetched from the Firestore.

You can also use LiveData to send new data fetched from Firestore to your activity or fragment instead of using listeners.

public static Vehicle v;

// method return type changed to void
// public static Vehicle tessst() {
public static void tessst() {

    v = new Vehicle();

    DocumentReference docRef = db.collection("vehicles").document("123");
    docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {

            if(task.isSuccessful()){
                DocumentSnapshot documentSnapshot = task.getResult();
                if(documentSnapshot !=null){
                    v  = documentSnapshot.toObject(Vehicle.class);

                    // TODO
                    // mListener will be called from here 
                    // or 
                    // set the value of the liveData here
                    // to send the object v obtained 

                }
            }
        }
    });
    // return v;
}
Dhara Bhavsar
  • 345
  • 4
  • 11