本文介绍了无法从Firebase数据库检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从我的Firebase数据库中检索值.
I am trying to retrieve values from my firebase database.
它正在onDataChange()函数中显示值,但无法显示其中的值.
It is displaying the values in onDataChange() function but unable to display the values out of it .
代码:
public Records readtraditional(String email)
{
final Records record = new Records();
final String[] name = new String[1];
myRef.child(email).child("name").addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
name[0] = dataSnapshot.getValue().toString() ;
//Printing value of name here
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.i("name in ","H"+name[0]);
//Unable to print value of name here
record.setName(name[0]);
return record;
}
推荐答案
正如我在注释中提到的,对Firebase的调用是异步的.如果您想让方法返回Records
对象,则应使用callback:
As I mentioned in my comment call to Firebase is asynchronous. If you want your method to return Records
object you should use callback:
public void readtraditional(String email, MyCallback callback)
{
final Records record = new Records();
final String[] name = new String[1];
myRef.child(email).child("name").addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
name[0] = dataSnapshot.getValue().toString() ;
record.setName(name[0]);
callback.onSuccess(record)
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
接口:
public interface MyCallback{
void onSuccess(Records record)
}
您可以这样调用此方法:
And you can call this method like this:
readtraditional(mystring,new MyCallback{
@Override
void onSuccess(Records record){
//do whatever you want
}
});
这篇关于无法从Firebase数据库检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!