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