【发布时间】: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