我是firebase的新用户,我试图在Users
中获取数据的大小,其中Users
具有不同的records
,并且每条记录都有两个属性Name
和Contact
。我希望在cont中获得records
的大小。我试图在Android应用程序中使用java。
数据库的结构看起来像这样
Users
Records
Name
Contact
我想得到记录的数量。
答案 0 :(得分:2)
假设您的数据库结构如下所示:
Firebase-root
|
--- users
|
--- uidOne
| |
| --- name: "NameOne"
| |
| --- contact: "ContactOne"
|
--- uidTwo
|
--- name: "NameTwo"
|
--- contact: "ContactTwo"
要获得用户数,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
Log.d("TAG", "count= " + count);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
答案 1 :(得分:0)
使用值侦听器
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
//You can use the single or the value.. depending if you want to keep track
thismyRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap: dataSnapshot.getChildren()) {
Log.e(snap.getKey(),snap.getChildrenCount() + "");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
答案 2 :(得分:0)
您所需要的只是DataSnapshot。
另请查看此SO question
答案 3 :(得分:0)
要获得计数,只有一行
dataSnapshot.getChildrenCount();
请参阅下面的答案
ref.addListenerForSingleValueEvent(new ValueEventListener() { //ref will be your desired path where you want to count children
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) { // Check for data snapshot has some value
dataSnapshot.getChildrenCount() // check for counts of data snapshot children
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});