这样做的原因是因为 firebase 是异步执行的,而您编码时就好像这一切都是同步发生的。这是什么意思 ?这意味着 firebase 调用不会立即从服务器返回值,需要一些时间才能获取该值,但其余代码在响应返回之前正在执行,这就是您遇到问题的原因。因此,即使这段代码执行:
if (service_type.equals("support")){
DocumentReference docRef = firestore_popup.collection("param_data_app").document("support_case_numbers");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
String consecutive = document.get("consecutive").toString();
if (consecutive.equals(null)) {
int random = new Random().nextInt(117) + 4;
case_number_consecutive = "IOC-09"+random;
} else {
case_number_consecutive = consecutive; UpdateCaseNumbersConsecutive("support");
}
} else {
int random = new Random().nextInt(117) + 4;
case_number_consecutive = "IOC-09"+random;
}
}
});
}
当响应返回时,您的其他代码:
Map<String, Object> user_cases_information = new HashMap<>();
user_cases_information.put("case_number", case_number_consecutive);
已经完成并被调用,然后你永远不会从 firebase 获得实际值。
看看我的回答:如何在 Java 中将 Facebook Graph api 的结果添加到数组列表中 https://stackoverflow.com/questions/57297762/how-to-add-results-of-facebook-graph-api-to-array-list-in-java/57297972#57297972如果你需要帮助,我会帮你做类似的东西
您可以执行以下操作:
interface Callback{
void firebaseResponseCallback(String result);//whatever your return type is.
}
更改此方法的签名,如下所示:
public void getCaseNumber(Callback callback) {
将您的代码更改为:
if (service_type.equals("support")){
DocumentReference docRef = firestore_popup.collection("param_data_app").document("support_case_numbers");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
String consecutive = document.get("consecutive").toString();
if (consecutive.equals(null)) {
int random = new Random().nextInt(117) + 4;
case_number_consecutive = "IOC-09"+random;
} else {
case_number_consecutive = consecutive; UpdateCaseNumbersConsecutive("support");
}
} else {
int random = new Random().nextInt(117) + 4;
case_number_consecutive = "IOC-09"+random;
}
callback.firebaseResponseCallback(case_number_consecutive);
}
});
}
然后,当你打电话时getCaseNumber
:
getCaseNumber(new Callback() {
@Override
public void firebaseResponseCallback(String result) {
here, this result parameter that comes through is your api call result to use, so result will be your case number, so make your objects inside this method, not outside
}
});
}
Edit
我专门针对这些类型的问题发表了这篇文章:如何从android中的任何异步操作中获取数据 https://stackoverflow.com/questions/57330766/how-to-get-data-from-any-asynchronous-operation-in-android/57330767#57330767