How to use a value outside dataSnapshot function?

放肆的年华 提交于 2021-02-05 12:08:23

问题


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) {

                    }
                });

Can anyone help me?


回答1:


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

After attaching listener

Got data

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().

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.

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



来源:https://stackoverflow.com/questions/56283386/how-to-use-a-value-outside-datasnapshot-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!