我使用firebase存储数据,但我无法获取数据列表 从firabse,具体我想得到人物对象的arraylist。 这是班上人
public class Person {
private String name;
private String username;
public Person() {
}
public Person(String name, String username) {
this.name = name;
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
,这是数据结构
答案 0 :(得分:2)
您可以使用任何事件侦听器获取数据。这是与子事件监听器。
List<Person> persons = new ArrayList<>();
ChildEventListener listener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
persons.add(person);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Person person = dataSnapshot.getValue(Person.class);
persons.remove(person);
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseDatabase.getInstance().getReference().child("persons").addChildEventListener(listener);
答案 1 :(得分:1)
Ugur B 答案也是正确答案。在这里,您也可以使用 ValueEventListener 来获取firebase数据...
ArrayList<String> arrayListVal = new ArrayList<String>();
fbref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Person person = postSnapshot.getValue(Person.class);
//Adding it to a ArrayList
arrayListVal.add(person);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Failed to fetch data: " + firebaseError.getMessage());
}
});