我正在为一所教育学院开发一个应用程序,下面的代码片段检索了一个Parent对象,该对象以前被推送到Firebase实时数据库,以便在该Student对象也被推送到数据库之前链接到Student对象。。
如果这是该特定家长的第一个学生(孩子(,则代码运行良好。。换句话说,此Parent对象具有其子对象(ren(的列表。如果此列表为空或为null,则代码工作正常。。但是,如果要推送的Student是同一个父对象的第二个子对象,这意味着检索到的parent对象将包含一个子对象列表,我得到的是:
com.google.firebase.database.DatabaseException: Expected a List while deserializing, but got a class java.util.HashMap
以下是检索Parent对象的方法:
private void getCorrespondingParent(){
DatabaseReference correspondingParentReference = FirebaseDatabase.getInstance().getReference()
.child("parents").child(mUserPhone);
correspondingParentReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mParent = snapshot.getValue(Parent.class);
// null out the children field because the Parent object will be saved in the Student object
// this avoids having a parent with children list that each Student in it has a parent object that
// has a list of students...
mParent.setChildren(null);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.w(LOG_TAG, "loadPost:onCancelled", error.toException());
}
});
}
数据库位于获取dataSnapshot值的行中:mParent = snapshot.getValue(Parent.class);
这是数据库中的Parent节点:数据库参考
这是Parent对象的POJO类:
public class Parent {
private int accType;
private String name;
private String uid;
private String phone;
private String whatsappPhone;
private String know;
private List<Student> children;
public Parent() {}
public Parent(String name, String uid, String phone, String whatsappPhone, String know) {
this.accType = 3;
this.name = name;
this.uid = uid;
this.phone = phone;
this.whatsappPhone = whatsappPhone;
this.know = know;
}
public int getAccType() {
return accType;
}
public void setAccType(int accType) {
this.accType = accType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getWhatsappPhone() {
return whatsappPhone;
}
public void setWhatsappPhone(String whatsappPhone) {
this.whatsappPhone = whatsappPhone;
}
public String getKnow() {
return know;
}
public void setKnow(String know) {
this.know = know;
}
public List<Student> getChildren() {
return children;
}
public void setChildren(List<Student> children) {
this.children = children;
}
}
好的,我发现了问题所在。。
如父对象节点中所示
我使用学生名称作为student对象的键,还使用List将父对象的子对象存储在parent对象中。。事实证明,如果你使用列表,你就不能使用自定义键,列表项键只是它的索引,不能更改。。我切换到Map<String, Student> children
而不是List<Student> children
,现在它工作得很好。
推送代码无需更改:
DatabaseReference newChildReference = FirebaseDatabase.getInstance().getReference()
.child("parents").child(parentPhone).child("children").child(childKey);
newChildReference.setValue(mNewStudent);
newChildReference.push();
mNewStudent是一个Student对象,用于保存新添加的学生数据。