getChildrenCount的Firebase Datasnapshot设置为零 [英] Firebase Datasnapshot for getChildrenCount sets to zero

查看:81
本文介绍了getChildrenCount的Firebase Datasnapshot设置为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让孩子数作为我的Firebase数据库参考时出现问题.

Have a problem when getting the children count for my firebase database reference.

我正在使用

private long childs;

此变量在onCreate中设置如下:

this variable gets set in onCreate like this:

    ref_1 = new Firebase("https://xxxxxxxxxx-xxxxx.xxxxxxxxx.com/traning/crossfit/level"+condition);
    ref_1.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            childs = dataSnapshot.getChildrenCount();
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });

如果我在dataSnapshot上调试了此代码,它会计算子项及其正确的数目,但是当在文件的其他位置使用此全局变量子项时,它会以某种方式设置为零.

If i debug this code at the dataSnapshot it have counted the children and its correct, but when using this global variable childs on other places in the file there is somehow set to zero.

推荐答案

之所以会发生这种情况,是因为onDataChange()方法被称为异步方法.您不能简单地将childs变量设置为全局变量,并在类中所需的任何位置使用它.之所以发生这种情况,是因为甚至在从数据库获取数据之前就调用了onDataChange()方法.为了更好地理解,请从此

This is happening because onDataChange() method is called asynchronous. You cannot simply make childs variable global and use it anywhere you want in your class. This is happening because onDataChange() method is called even before you are getting the data from the database. For a better understanding, please see my answer from this post.

要快速修复,只需在onDataChange()方法内部使用childs变量的值即可.

For a quick fix, just use the value of your childs variable, only inside the onDataChange() method.

这篇关于getChildrenCount的Firebase Datasnapshot设置为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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