[英]Trying to retrieve value from Firebase, but getting null?
As you can see from the code below, I output retrievedValue
from inside onDataChange()
which works as intended. 正如你可以从下面的代码,我输出中看到retrievedValue
从里面onDataChange()
如预期其中工程。 But I can't output retrievedValue
from another place because it returns null
. 但是我不能从另一个地方输出retrievedValue
到的null
因为它返回null
。
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
retrievedValue = (Long) dataSnapshot.getValue();
System.out.println(retrievedValue); //this line works
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println(retrievedValue); //this line returns null! How can I fix this?
this line returns null! 这行返回空值! How can I fix this? 我怎样才能解决这个问题?
I don't think you understand how asynchronous code works... First, nothing is returned null. 我不认为您了解异步代码的工作原理……首先,没有任何东西返回null。 Nothing has been assigned yet. 尚未分配任何东西。
Your code is the exact same as this. 您的代码与此完全相同。
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
System.out.println(retrievedValue); //this line returns null!
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
retrievedValue = (Long) dataSnapshot.getValue();
System.out.println(retrievedValue); //this line works
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
There is nothing to fix because you are using Firebase wrong. 由于您使用的Firebase错误,因此无法修复。
If you need retrievedValue
, then you should put all related code into (or after, like via another method) onDataChange
如果您需要retrievedValue
,那么你应该把所有相关的代码为(或之后,如通过另一种方法) onDataChange
For example 例如
private Long retreivedValue; // starts as null
public static void updateSomething(Long data) {
System.out.println(data); // this line works
}
public static void main(String... args) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
retrievedValue = (Long) dataSnapshot.getValue();
updateSomething(retrievedValue);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.