我必须将响应从firebase返回到另一个函数,该函数将使用该数据进行进一步处理。
public ArrayList<String> getDatas(String number) {
final ArrayList<String> requestList = new ArrayList<>();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference reference = database.getReference("Users").child(number).child("request_list");
final DatabaseReference requestReference = database.getReference("Request");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "onDataChange: ");
for (final DataSnapshot data : dataSnapshot.getChildren()) {
Log.i(TAG, "onDataChange: data: " + data.getValue());
requestList.add(data.getValue().toString());
}
Log.i(TAG, "onDataChange: for ended");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return requestList;
}
由于firebase操作是异步的,我无法等待数据返回。有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
您可以使用回调方法
http://developer.android.com/reference/java/util/concurrent/Callable.html
通过使用Callable接口,您可以将参数作为函数传递,我添加了一个简单的代码片段以便理解。
public class MainActivity<V> extends Activity {
Callable<String> doLogin=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doLogin=new Callable<String>() { //created but not called now.
@Override
public String call() throws Exception {
//make some piece of code
return "something"; //or false
}
};
CheckSession checkSession=new CheckSession("sessionName");
String sessionKey="";
try { //we are sending callable to the DAO or any class we want
sessionKey=checkSession.getSessionKey(doLogin);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class CheckSession{
String sessionName="";
Callable<String> func=null;
public CheckSession(String sessionName) {
super();
this.sessionName = sessionName;
}
public String getSessionKey(Callable<String> doLogin) throws Exception{
func=doLogin;
return (String) func.call();
}
}