I have a problem with assigning a value to a variable out of the OnSuccessListener. As you see in the code, first, I'm trying to write the value of abc into log inside the Listener and then outside I debug the value of the same string after the listener completed work, but in a log file I see first "after: null" and only after that "result = testField".
I suppose, that the point is that the listener does the task asynchronously, but I don't know when it finishes. I 'fixed' the problem using Thread.sleep, but it isn't the solution. Does anyone know the correct method of assgning the field value to a variable?
String abc;
private void getInfo(String uid) {
DocumentReference doc = FirebaseFireStore.getInstance().document("sb/base");
store.collection("users").document(uid).get().addOnSuccessListener(
new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (!documentSnapshot.exists())
log("onSuccess: EMPTY");
else {
abc = new JSONObject(documentSnapshot.getData()).toString();
log("result = " + abc);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(applicationManager.activity.getApplicationContext(),
"ERROR", Toast.LENGTH_SHORT).show();
}
});
log("after: " + abc);
}