Reputation: 43
I'm a bit puzzled by strange problem.
I'm trying to access a value on a Firebase database.
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]);
The time
variable is what I want to access.
The Logcat shows the following:
Location frequency is 5 seconds.
Time is: 0
What seems to be the problem? It seems to access the database fine, but the variable isn't updated. What am I doing wrong?
Thanks in advance!
Upvotes: 1
Views: 258
Reputation: 514
It is 0 because it is not updated yet, as firebase runs a async task to complete the listeners.
You are accessing Log.e(TAG, "Time is: " + time[0]); line of code outside onComplete listener. This line of code is executed before even the firebase has completed its fetching. You can implement a method call and access the Time from there.
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]);
}
Upvotes: 2