Firebase无法将检索到的数据保存到ArrayList [英] Firebase can't save retrieved data to ArrayList

查看:103
本文介绍了Firebase无法将检索到的数据保存到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检索数据有效,但是我无法将检索到的数据保存到ArrayList中.在"onDataChanged()"方法之后,ArrayList配置文件"似乎具有2个值,但是在return语句中它具有0个值.

Retrieving data works but I can't save the retrieved data into an ArrayList. Right after the "onDataChanged()" method ArrayList "profile" seems to have 2 values, but on the return statement it has 0.

static List<Profile> profiles = new ArrayList<Profile>();
static DatabaseReference dbr;

public static List<Profile> loadProfiles(Context context){

    dbr = FirebaseDatabase.getInstance().getReference().child("users").child("hiring");
    dbr.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            //String value = dataSnapshot.getValue(String.class);
            //Log.d("hello", "Value is: " + value);
            List<Profile> profiles2 = new ArrayList<>();

                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Profile profile = snapshot.getValue(Profile.class);
                    //Log.d("hello", profile.getCompanyName());
                    profiles2.add(profile);

                }

                profiles = profiles2;
                dbr.removeEventListener(this);
        }




        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w("hello", "Failed to read value.", error.toException());
        }
    });

    return profiles;

}

推荐答案

您现在无法返回尚未加载的内容.换句话说,您不能简单地在onDataChange()方法之外返回profiles列表,因为由于此方法的异步行为,该列表将始终是empty.这意味着,当您尝试返回该方法之外的结果时,数据尚未从数据库中加载完毕,因此无法访问.

You cannot return something now that hasn't been loaded yet. With other words, you cannot simply return the profiles list outside the onDataChange() method because it will always be empty due the asynchronous behaviour of this method. This means that by the time you are trying to return that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

此问题的快速解决方案是仅在onDataChange()方法内使用profiles列表,否则我建议您从此 视频 更好的理解.

A quick solve for this problem would be to use the profiles list only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

这篇关于Firebase无法将检索到的数据保存到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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