java - 如何遍历数据库以检索评论部分
问题描述
我正在尝试遍历 firebase 以检索每个用户提交的所有评论,并且还添加了他们的用户名,以便我可以匹配它们,因为每个评论对用户来说都是独一无二的。我只是发现附加他们的用户名而不是使用我的图片中显示的增量值更容易......我可以让数组显示在屏幕上但是当使用数组检索 info.getReview() 方法时,我变得空...我猜,第二个数组有两个用户名钢琴和音乐家。应该只说音乐家正确吗?我不确定我是否在这里正确执行此操作,但我认为我应该使用数组来循环...
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Medical Clinics"); // getReference() is the root
reference.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
int count = (int) snapshot.child("ID").getChildrenCount();
Information info = snapshot.getValue(Information.class);
for (i = 0; i < count; i++) {
String Id = String.valueOf(snapshot.child("ID").getValue());
Id = Id.replace("{", "");
Id = Id.replace("}", "");
Id = Id.replaceAll("Id by", "");
String[] username = Id.split("=");
// Id = Id.substring(Id.indexOf("=") + 1);
Information info2 = snapshot.child("Reviews, Rating and Services by " + username[i]).getValue(Information.class);
// for (int i =0; i < words.length; i++) {
assert info != null;
// assert info2 != null;
String txt;
// if (info2.getReview().isEmpty()) {
// Toast.makeText(View_Review.this, "There are no Reviews provided yet for this particular Medical Clinic!", Toast.LENGTH_SHORT).show();
// return;
// } else {
// txt = "Medical Clinic: " + info.getName() + "\n\nReviews: " + info2.getReview(); //+ "\n\nService 1: " + info2.getServices() + "\n\nService 2: " + info2.getServices2() + "\n\nService 3: " + info2.getServices3() + "\n\nService 4: " + info2.getServices4() + "\n\nService 5: " + info2.getServices5() + "\n\nService 6: " + info2.getServices6() + "\n\nService 7: " + info2.getServices7() + "\n\nService 8: " + info2.getServices8() + "\n\nRating: " + info2.getRating();
txt = "ID: " + username[i];
System.out.println(Id);
// System.out.println(info2.getReview());
list.add(txt);
}
adapter.notifyDataSetChanged();
}
// }
}
解决方案
似乎您的结构可以简化如下:
-RingWood Family Medical Center
|
-MJ0jfdsk2(unique id for user)
|
-rating
-review
-services3
-username
-MJ1kjksf2(unique id for user 2)
|
-rating
-review
-services3
-username
...
通过执行上述操作,您可以轻松地遍历 RingWood 家庭医疗中心的孩子并获得用户名和评论。
有关 JSON 结构最佳实践的更多信息,您可以从 Firebase 页面阅读以下内容。参考:https ://firebase.google.com/docs/database/web/structure-data
快乐编码!
推荐阅读
- reactjs - react.js - 使用自定义路径运行 npm run build
- xml - 错误:无法找到或加载主类 com.sun.tools.internal.xjc.XJCFacade
- function - 使用变量时真正发生了什么?
- matlab - 防止彩条在 MATLAB 中调整图像大小
- angular - 如何在 Angular 的 Rxjs 6 中使用运算符
- javascript - javascript中表单提交的返回方法
- android - 生成请求代码时未显示通知
- ios - 在 iOS 和 macOS 玩家之间使用 GameCenter 启用多人游戏
- bash - 简单的 shell 脚本程序中的错误
- javascript - 为什么带有 Vue.js 的 Webpack 会产生这么大的构建文件?