android-Firebase从datasnapshot返回空值,为什么? [英] android - Firebase return null value from datasnapshot Why?

查看:72
本文介绍了android-Firebase从datasnapshot返回空值,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些麻烦,其中包含以下代码:

I am having some touble with the following code snipped:

mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void  onDataChange(DataSnapshot dataSnapshot) {
        size = (int) dataSnapshot.getChildrenCount();   
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});
viewHolder.setCount(size);

大小返回null,但我不明白为什么.我想将计数值传递给recyclerview.

The size returns null but I don't understand why. I want to pass count values to recyclerview.

推荐答案

数据是从Firebase异步加载的.这意味着执行代码的顺序与预期的不同.您可以通过在代码中添加一些日志语句来最轻松地看到这一点:

The data is loaded from Firebase asynchronously. This means that the order in which your code is execute is not what you're likely expecting. You can most easily see this by adding a few log statements to the code:

System.out.println("Before addListenerForSingleValueEvent");
mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void  onDataChange(DataSnapshot dataSnapshot) {
        System.out.println("In onDataChange");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});
System.out.println("After addListenerForSingleValueEvent");

此输出为:

在addListenerForSingleValueEvent之前

Before addListenerForSingleValueEvent

在addListenerForSingleValueEvent之后

After addListenerForSingleValueEvent

在onDataChange

In onDataChange

这可能不是您所期望的!数据是从Firebase异步加载的.并且,该方法继续,而不是等待它返回(这将导致应用程序无响应"对话框).然后,当数据可用时,将调用onDataChange.

This is probably not what you expected! The data is loaded from Firebase asynchronously. And instead of waiting for it to return (which would cause an "Application Not Responding" dialog), the method continues. Then when the data is available, your onDataChange is invoked.

要使程序正常运行,您需要将需要数据的代码移入 onDataChange方法:

To make the program work, you need to move the code that needs the data into the onDataChange method:

mCevap.child(post_key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void  onDataChange(DataSnapshot dataSnapshot) {
        System.out.println("size ="+dataSnapshot.getChildrenCount());
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});

这篇关于android-Firebase从datasnapshot返回空值,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆