【问题标题】:Firebase can't save retrieved data to ArrayListFirebase 无法将检索到的数据保存到 ArrayList
【发布时间】:2018-05-29 02:18:50
【问题描述】:

检索数据有效,但我无法将检索到的数据保存到 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;

}

【问题讨论】:

  • 发生这种情况是因为 addListenerForSingleValueEvent 是异步的。

标签: java android firebase firebase-realtime-database


【解决方案1】:

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

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

编辑: 2021 年 2 月 26 日

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

还有以下视频:

【讨论】:

  • 是的,我通过对“onDataChange()”中的数据做所有我需要做的事情来解决这个问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
相关资源
最近更新 更多