如何在dataSnapshot函数之外使用值? [英] How to use a value outside dataSnapshot function?

查看:47
本文介绍了如何在dataSnapshot函数之外使用值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我得到了孩子的数量,但是我想在onDataChange方法之外使用它.

In the code below i get the number of children but i want to use it outside the onDataChange method.

              mRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot)
                    {
                        DateStorage dateStorage = null;
                        for (DataSnapshot result : dataSnapshot.getChildren()) 
                    {


                     Log.e(result.getKey(),result.getChildrenCount() + "");
                      in[0] = result.getChildrenCount();

                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

有人可以帮助我吗?

推荐答案

数据是从Firebase异步加载的.在加载数据时,您的主代码将继续运行,然后,当数据可用时,将调用 onDataChange 方法.如果添加一些日志语句,这最容易理解:

Data is loaded from Firebase asynchronously. Your main code continues to run while the data is loading, and then when the data is available the onDataChange method is called. What that means is easiest to see if you add a few log statements:

Log.d("TAG", "Before attaching listener");
mRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot)
    {
        Log.d("TAG", "Got data");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});
Log.d("TAG", "After attaching listener");

运行此代码时,它将记录:

When you run this code, it logs:

在附加侦听器之前

Before attaching listener

附加监听器后

获得数据

这可能不是您期望的顺序,但是在调用异步API时是完全正常的.它解释了为什么在 onDataChange()之外打印时会得到错误的值.

This is probably not the order you expected, but is completely normal when calling asynchronous APIs. And it explains why you'll get the wrong value if you print it outside of the onDataChange().

问题不在于您不能在 onDataChange()之外使用数据,而是必须确保 onDataChange()已运行之前使用数据.

The problem is not that you can't use the data outside of the onDataChange(), the problem is that you must ensure that onDataChange() has run before you use the data.

最简单的方法是将所有需要数据库数据的代码放在 onDataChange 方法的内部.但是,您也可以创建自己的回调接口,并将其传递到加载数据的方法中.有关这两种方法的示例,请在此处查看我的答案: getContactsFromFirebase()方法返回一个空列表

The simplest way to do that is to put all code that requires data from the database inside the onDataChange method. But you can also create your own callback interface, and pass that into the method where you load the data. For an example of both of these approaches, see my answer here: getContactsFromFirebase() method return an empty list

这篇关于如何在dataSnapshot函数之外使用值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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