我正在尝试从我的firebase数据库中检索值。
它在onDataChange()函数中显示值,但无法显示其中的值。
代码:
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;
}
答案 0 :(得分:1)
正如我在评论中提到的,对Firebase的调用是异步的。如果您希望方法返回Records
对象,则应使用回调:
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)
}
你可以这样调用这个方法:
readtraditional(mystring,new MyCallback{
@Override
void onSuccess(Records record){
//do whatever you want
}
});