java - Firebase 无法将检索到的数据保存到 ArrayList

标签 java android firebase firebase-realtime-database

检索数据可以工作,但无法将检索到的数据保存到 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;

}

最佳答案

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

此问题的快速解决方案是仅在 onDataChange() 方法中使用 profiles 列表,否则我建议您查看我的答案的最后部分这个 post 其中我解释了如何使用自定义回调来完成它。您还可以看看这个video 为了更好地理解。

编辑:2021 年 2 月 26 日

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

以及以下视频:

关于java - Firebase 无法将检索到的数据保存到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50575464/

相关文章:

java - 使用 freemarker 生成要在电子邮件中发送的 html,他们是否无论如何都要使用渲染的 jsp 页面?

java - 用于匹配文本文件的正则表达式

java - Elasticsearch - 升级到 2.1.1 后搜索失败

android - Android Studio 中的 Firebase android jars 文档/javadoc

Firebase 存储规则匹配不带用户 ID 扩展名的文件名

android - 无法使用 Flutter 将文件上传到 FirebaseStorage

Java 将 Select 转换为 Enum

android - 设置 subview 的中心重心更改水平布局中另一个 subview 的布局对齐方式?

android - 在 sleep 模式下使用音量按钮(音乐播放器风格)

Android: ScrollView 问题