问题描述
我知道这已经被问了很多,但我仍然可以让它工作.这是我的代码:
I know this has been asked a lot but I still can get it to work. Here's my code:
private int test;
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Users");
test = 0;
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(userID))
test = 1;
else
test = 2;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.d(TAG, "Test = " + test);
Firebase 上的内容:
Here's what on Firebase:
- appname-e545e
- 用户
- 用户 ID
我不知道为什么,但变量test"总是返回值 0,这意味着 addListenerForSingleValueEvent 不起作用.感谢您的帮助
I don't know why but the variable "test" always return value 0, which means addListenerForSingleValueEvent didn't work. Thanks for helping in advanced
推荐答案
从 Firebase 异步加载数据.到您的日志
test
时,onDataChange
尚未运行.The data is loaded from Firebase asynchronously. By the time your log
test
, theonDataChange
hasn't run yet.要查看此操作,请添加更多日志记录inside
onDataChange
:To see this in action, add some more logging inside
onDataChange
:私有int测试;
test = 0; userRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.hasChild(userID)) { test = 1; } else { test = 2; } Log.d(TAG, "Test2 = " + test); } @Override public void onCancelled(DatabaseError databaseError) { throw databaseError.toException(); // Don't ignore errors } }); Log.d(TAG, "Test = " + test);
现在您将首先看到:
测试 = 0
然后一旦数据加载完毕并且
onDataChange
被调用:And then once the data has loaded and
onDataChange
gets called:测试 = 1
或
测试 = 2
因此,您应该始终在
onDataChange()
中放置(或调用)需要数据库中数据的代码.For this reason you should always put (or call) the code that needs the data from the database from within
onDataChange()
.这篇关于Android Firebase addListenerForSingleValueEvent 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- 用户