Firebase变量未更新

时间:2018-11-10 14:37:34

标签: android firebase firebase-realtime-database

我为一个奇怪的问题感到困惑。

我正在尝试访问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

似乎是什么问题?似乎可以很好地访问数据库,但是该变量未更新。我在做什么错了?

谢谢!

1 个答案:

答案 0 :(得分:2)

它为0,因为它尚未更新,因为firebase运行异步任务来完成侦听器。

您正在访问Log.e(TAG,“时间是:” + 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]);
}