您的代码中的问题在于您的字段名称CommentModel
类与数据库中的属性名称不同。你在你的CommentModel
类一个名为comment
但在你的数据库中我将其视为Comment
这是不正确的。名称必须匹配。当您使用名为的 getter 时getComment()
,Firebase 正在数据库中查找名为的字段comment
并不是Comment
。看小写的c
字母与大写字母C
?
有两种方法可以解决此问题。第一个是通过根据以下内容重命名字段来更改模型类Java 命名约定。所以你的模型类应该是这样的:
public class CommentModel {
private String comment, commentDate, profilePic, commentUser;
public CommentModel() {}
public CommentModel(String comment, String commentDate, String profilePic, String commentUser) {
this.comment = comment;
this.commentDate = commentDate;
this.profilePic = profilePic;
this.commentUser = commentUser;
}
public String getComment() { return comment; }
public String getCommentDate() { return commentDate; }
public String getProfilePic() { return profilePic; }
public String getCommentUser() { return commentUser; }
}
看这个例子,有private
字段和公共吸气剂。还有一个更简单的解决方案,直接在公共字段上设置值,如下所示:
public class CommentModel {
public String comment, commentDate, profilePic, commentUser;
}
现在只需删除当前数据并使用正确的名称再次添加即可。该解决方案仅在您处于测试阶段时才有效。
还有第二种方法,就是使用annotations
。因此,如果您更喜欢使用私有字段和公共 getter,则应该使用属性名称注释仅在 getter 前面。所以你的CommentModel
类应该如下所示:
public class CommentModel {
private String comment, commentDate, profilePic, commentUser;
public CommentModel() {}
public CommentModel(String comment, String commentDate, String profilePic, String commentUser) {
this.comment = comment;
this.commentDate = commentDate;
this.profilePic = profilePic;
this.commentUser = commentUser;
}
@PropertyName("Comment")
public String getComment() { return comment; }
@PropertyName("CommentDate")
public String getCommentDate() { return commentDate; }
@PropertyName("ProfilePic")
public String getProfilePic() { return profilePic; }
@PropertyName("CommentUser")
public String getCommentUser() { return commentUser; }
}
也不要忘记开始倾听变化。
附:在你的班级中,它应该是:
this.commentDate = commentDate;
and not:
commentDate = commentDate;