奇怪的问题让我有点不解。
我正在尝试访问 Firebase 数据库中的值。
final long[] time = {0};
firebaseAuth = FirebaseAuth.getInstance();
email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
DocumentReference docRef = db.collection("location_times").document(email);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.e(TAG, "DocumentSnapshot data: " + document.get("time"));
time[0] = (long) document.get("time");
Log.e(TAG, "Location frequency is " + time[0] + " seconds.");
} else {
Log.e(TAG, "No such document");
}
} else {
Log.e(TAG, "get failed with ", task.getException());
}
}
});
Log.e(TAG, "Time is: " + time[0]);
time
变量是我想要访问的。
Logcat 显示以下内容:
Location frequency is 5 seconds.
Time is: 0
问题是什么?似乎可以正常访问数据库,但变量未更新。我做错了什么?
提前致谢!
最佳答案
它是 0 因为它还没有更新,因为 firebase 运行一个异步任务来完成监听器。
您正在访问 Log.e(TAG, "Time is: "+ time[0]); onComplete 监听器外的代码行。这行代码甚至在 firebase 完成其获取之前就已执行。您可以实现方法调用并从那里访问时间。
final long[] time = {0};
firebaseAuth = FirebaseAuth.getInstance();
email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
DocumentReference docRef = db.collection("location_times").document(email);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.e(TAG, "DocumentSnapshot data: " + document.get("time"));
time[0] = (long) document.get("time");
Log.e(TAG, "Location frequency is " + time[0] + " seconds.");
showTime(); // Added a method call
} else {
Log.e(TAG, "No such document");
}
} else {
Log.e(TAG, "get failed with ", task.getException());
}
}
});
public void showTime(){ // perform your action after the firebase task is completed
Log.e(TAG, "Time is: " + time[0]);
}
关于android - Firebase 变量未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240001/