[英]Firebase why onChildAdded parameter s returns null
監聽數據時,我得到一個奇怪的結果。
對於節點“ allstudents”上的3個孩子,onchildadd方法為第0個元素返回null,但是,將第0個pushid分配給第一個元素,依此類推。
當我進行調整時,使用null觸發ID( -Kjw7V4jSphLBYs7Z_wx
)onChildChanged時,在FB控制台onChildChange上調整ID( -Kjw7bRY7AkJnGpOGJEw
)返回不同的ID( -Kjw7YchGZLamQmWTTc5
?
日志貓
E/String: onChildAdded:null
E/String: onChildAdded:-Kjw7V4jSphLBYs7Z_wx
E/String: onChildAdded:-Kjw7YchGZLamQmWTTc5
E/String: onChildChanged:-Kjw7YchGZLamQmWTTc5
E/String: onChildChanged:-Kjw7V4jSphLBYs7Z_wx
E/String: onChildChanged:null
規則:
"teachers": {
"$teacherID": {
".read": "auth != null && auth.uid == $teacherID",
".write": "auth != null && auth.uid == $teacherID",
".validate":"root.child('teacherids').child(newData.child('tID').val()).exists()"
}
},
// teachers can r/w student profiles, and the students can also r/w their own profile
"students": {
"$studentID": {
".read": "auth != null && (root.child('teachers').child(auth.uid).exists() || auth.uid == $studentID)",
".write": "auth != null && (root.child('teachers').child(auth.uid).exists() || auth.uid == $studentID)",
".validate":"root.child('studentids').child(newData.child('rollnr').val()).exists()"
}
},
"allstudents":{
".read": "auth != null && (root.child('teachers').child(auth.uid).exists() || root.child('students').child(auth.uid).exists() )",
".write": "auth != null && (root.child('teachers').child(auth.uid).exists() || root.child('students').child(auth.uid).exists() )"
}
向節點添加數據
mDatabase.child("allstudents").push().setValue(allstudentnode);
檢索/收聽數據
mDatabase.child("allstudents").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildAdded:"+s);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildChanged:"+s);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.e(TAG, "onChildRemoved:"+dataSnapshot.toString());
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.e(TAG, "onChildMoved:"+s);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled:"+databaseError.toString());
}
});
在代碼中的有效數據使用,你需要從獲取數據出來dataSnapshot
對象使用字符串代替s
從onChildAdded()
方法。
正如您在官方文檔中所看到的那樣, String s
實際上代表了String previousChildName
,這就是您在代碼中擁有上一個孩子的方式。
希望能幫助到你。
試試這個
mDatabase= FirebaseDatabase.getInstance();
mDatabase.getReference("allstudents").addValueEventListener(new
ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dst : dataSnapshot.getChildren()){
String key = dst.getKey();
Log.e(TAG, "onChildAdded:"+key);
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.