首页 > 解决方案 > Firebase 无法将检索到的数据保存到 ArrayList

问题描述

检索数据有效,但我无法将检索到的数据保存到 ArrayList 中。在“onDataChanged()”方法 ArrayList 之后,“profile”似乎有 2 个值,但在 return 语句中它有 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;

}

标签: javaandroidfirebasefirebase-realtime-database

解决方案


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

此问题的快速解决方案是profiles仅在方法内部使用列表,否则我建议您查看这篇文章onDataChange()的答案的最后一部分,其中我解释了如何使用自定义回调来完成。您也可以观看此视频以更好地理解。

编辑: 2021 年 2 月 26 日

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

以及以下视频:


推荐阅读