如何获取数据库中所有“地板”元素的列表。如果我使用以下数据库,则我的列表应包含3个元素。列表应包含ID为1234、4321、2341的元素。
mydatabase
-buildings
--LNBxRoNBhVZyXniqe9t
---checked
---anzI
---anzA
---floors
----f1
-----1234
------description
------id
----f2
-----4321
------description
------id
--LXdsafRfasdf12asdfJ
---checked
---anzI
---anzA
---floors
----f1
-----2341
------description
------id
这是我的DAO:
private FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("buildings");
@Override
public void initialize() {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
List<Floors> list = new LinkedList<>();
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
????
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}});
答案 0 :(得分:2)
您将需要遍历从Firebase获得的DataSnapshot
。像这样
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot buildingSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot floorSnapshot: buildingSnapshot.child("floors").getChildren()) {
for (DataSnapshot numberSnapshot: floorSnapshot.getChildren()) {
Log.i(TAG, numberSnapshot.getKey()); // "1234", "4321", "2341"
Log.i(TAG, ""+numberSnapshot.child("id").getValue());
}
}
}
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
答案 1 :(得分:0)
如何获取数据库中所有“地板”元素的列表?
通过一种非常简单的方法,使用getChildren()
方法对数据库进行三次迭代。
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference buildingsRef = rootRef.child("buildings");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.child("floors").getChildren()) {
for(DataSnapshot d : ds.getChildren()) {
String key = d.getKey();
String description = d.child("description").getValue(String.class);
list.add(key);
Log.d("TAG", key);
}
}
}
//Do what you need to do with your list
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage());
}
};
buildingsRef.addListenerForSingleValueEvent(valueEventListener);
列表应包含ID为1234、4321、2341的元素
该列表将包含这三个ID。如果您尝试在logcat中打印列表,结果将是:
[1234, 4321, 2341]