0

I'm currently working on an android school project where we have some users which we need to access/pass data from. Normally we would be working with mySQL, but we have to use Firebase / Firestore for this project. What I need to be able to is accessing an object, extracting it, and converting it to a java.class object and passing it to a controller. I read around I need to use callbacks to access data outside 'onSucces()' method, but I can't seem to figure it out. The object is accessible inside the onCallback method, but I need to return it in the main method, so I can return to my Controller. I know this is an asynchronous process, but I'm only experienced with that in Javascript. The comments in the code explain what I want to do, Thank you!

public FirebaseFirestore db;
private static final String TAG = "userLog" ;

@Override
public UserDTO getUser(String userId) {

     readData(new MyCallback() {
        @Override
        public void onCallback(UserDTO user) {
            //Here the userobject is accesible, I can print the data with:
            System.out.println("UserName = " + user.getfName());
            //But THIS userobject I would like to return in this getUser method!
           
            Log.d(TAG, user.toString());
        }
    });
     
    //I need to be able to return the user object here, so I can use it in my Controller!
    return null;
}

public void readData(MyCallback myCallback) {
    DocumentReference docRef = db.collection("users").document(userId);
    docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {
            UserDTO user = documentSnapshot.toObject(UserDTO.class);
            myCallback.onCallback(user);
        }
    });
}

public interface MyCallback {
    void onCallback(UserDTO user);
}
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • There is no way you can return a DocumentSnapShot object as a result of a method. Firebase API is asynchronous. So please check the duplicate to see how can correctly use a custom callback. – Alex Mamo Nov 13 '20 at 09:00
  • @AlexMamo so what should I do to obtain an object from firebase? Can you point me in a direction? I just need to be able to get an object from the Firebase into my program, like you would do with resultsets in mySQL. Thanks – Christian Notarmaso Nov 13 '20 at 16:36
  • Any code that needs data from the database, needs to be inside the onSuccess method, or be called from there. – Alex Mamo Nov 13 '20 at 17:06

0 Answers0