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