老实说,我现在感觉很愚蠢,但我只是不明白......
我想得到一个"用户"我的Firebase实时数据库中的对象,所以我添加了一个ValueListener,对吗? 我有一个方法" getUser"有"用户"作为回报。在那里我用这个:
ValueEventListener valueListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren())
{
User u = snap.getValue(User.class);
if(u.getEmail().equals(userEmail))
{
//user = u;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
//Adding the Listener for Single Event
fref.child("User").addListenerForSingleValueEvent(valueListener);
//Using "u" here then
现在我没有看到一个很好的方式让用户" u"在那里,我怎么得到它?
我知道这应该是基础知识,但我只是不明白......
提前感谢:)
答案 0 :(得分:0)
怎么样:
private User targetUser;
@Override
protected void onStart() {
super.onStart();
final ValueEventListener userListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
userNameList = new ArrayList<>((ArrayList) dataSnapshot.getValue());
for (User u : userNameList) {
if (u.getEmail().equals(userEmail)) {
targetUser = u;
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: Failed to load User list.");
}
};
userlistReference.addValueEventListener(userListener);
mUserListListener = userListener;
//use targetUser reference but check if it is null(can be null)...
}
答案 1 :(得分:0)
您必须使用CountDownLatch - 此对象将让您等到实际调用侦听器之后才返回对象:
private User getUser() {
final User user = null ;
final CountDownLatch cdl = new CountDownLatch(1);
ValueEventListener valueListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren())
{
User u = snap.getValue(User.class);
if(u.getEmail().equals(userEmail))
{
user = u;
break ;
}
}
cdl.countDown();
}
@Override
public void onCancelled(DatabaseError databaseError) {
cdl.countDown();
}
};
//Adding the Listener for Single Event
fref.child("User").addListenerForSingleValueEvent(valueListener);
try {
cdl.await();
} catch (InterruptedException ie) {
}
return user ;
}
答案 2 :(得分:-1)
您只需要在班级上创建全局变量,例如:
private User myUser;
然后在听众内部做:
myUser = u;
这是最简单的方法......