2 回答
TA贡献1798条经验 获得超7个赞
这样做的原因是因为 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 获得实际值。
这是你可以做的事情:
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
}
});
}
TA贡献1815条经验 获得超6个赞
您在该代码中犯了一个错误。根据 firebase 最新版本,您只能在 .addOnCompleteListener/.addValueEvent/etc 函数中使用 firebase 数据库的值/字符串。
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()) {
/////////////////////////////call here everything related to it////////////////////////
}
});
}
在 firebase 外部添加完整监听器或添加值监听器,变量或对象值不会改变或保持不变!
添加回答
举报