等到 firebase 检索数据 [英] wait until firebase retrieves data
问题描述
我想构建一个在 FireBase
中返回 child
值的方法.我试图做这样的事情:
I want to build a method that returns a child
value in FireBase
. I tried to do something like this:
public String getMessage(){
root.child("MessagesOnLaunch").child("Message").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
message = (String) dataSnapshot.getValue();
Log.i("4r398", "work");
}
@Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("error", firebaseError.getMessage());
}
});
return message;
}
问题是该方法返回null
,这可能是因为该方法没有等到侦听器完成并返回null
,因为它的默认值消息代码>.我怎样才能让这个方法等到监听器发生然后返回值.
The problem is that the method returns null
that is probably because the method doesn't wait until the listener finishes and return null
because its the default value of message
.
How can I make this method wait until the listener occurs and then return the value.
推荐答案
制作界面
public interface OnGetDataListener {
//this is for callbacks
void onSuccess(DataSnapshot dataSnapshot);
void onStart();
void onFailure();
}
声明如下函数readData()
Declare the following function readData()
public void readData(Firebase ref, final OnGetDataListener listener) {
listener.onStart();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
listener.onSuccess(dataSnapshot);
}
@Override
public void onCancelled(FirebaseError firebaseError) {
listener.onFailure();
}
});
}
调用readData()函数如下
Call the readData() function as follows
readData(root.child("MessagesOnLaunch").child("Message"), new OnGetDataListener() {
@Override
public void onSuccess(DataSnapshot dataSnapshot) {
//got data from database....now you can use the retrieved data
}
@Override
public void onStart() {
//when starting
Log.d("ONSTART", "Started");
}
@Override
public void onFailure() {
Log.d("onFailure", "Failed");
}
});
readData() 可以在你的 getMessage() 方法中调用,甚至可以在 onCreate() 中调用
readData() can be called inside your getMessage() method or even inside onCreate()
这篇关于等到 firebase 检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!