Ad

How To Get Data From FireStore To Custom Object And Then Return It?

- 1 answer

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;
}
Ad

Answer

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;
}
Ad
source: stackoverflow.com
Ad