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

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

问题描述

检索数据有效,但我无法将检索到的数据保存到 ArrayList 中.在onDataChanged()"方法之后,ArrayListprofile"似乎有 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. In other words, you cannot simply return the profiles list outside the onDataChange() method because it will always be empty due to the asynchronous behavior 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 solution 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 answer 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.

2021 年 2 月 26 日

Feb 26th, 2021

有关更多信息,您可以查看以下文章:

For more info, you can check the following article:

还有以下视频:

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

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