我正在尝试从 firebase 的 DataSnapshot 获取数据。我遵循了 firebase 开发人员示例中的说明。当我尝试提取数据时,它显示为空,尽管我在 Android Studio 中运行调试器时可以看到数据。下面列出的是我正在使用的代码。
Query mQueryRef = mDatabase.child("users").child(mUserId).child("bullets");
// This type of listener is not one time, and you need to cancel it to stop
// receiving updates.
mQueryRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChild) {
// This will fire for each matching child node.
Bullet bullet = snapshot.getValue(Bullet.class);
String date = bullet.getDate();
String title = bullet.getTitle();
mEmailBody + "\n" + title + " " + date;
这是项目符号类:
public class Bullet {
// Bullet basics
private String title;
private String orderDate;
private String date;
private String action;
private String result;
private String impact;
// Default constructor required by Firebase
public Bullet (){
}
//Constructor
public Bullet (String title, String orderDate, String date, String action, String result, String impact) {
this.title = title;
this.orderDate = orderDate;
this.date = date;
this.action = action;
this.result = result;
this.impact = impact;
}
//Getters
public String getTitle() {return title;}
public String getOrderDate() {return orderDate;}
public String getDate() {return date;}
public String getAction() {return action;}
public String getResult() {return result;}
public String getImpact() {return impact;}
//Setters
public void setTitle(String title){
this.title = title;
}
public void setOrderDate(String orderDate){
this.orderDate = orderDate;
}
public void setDate(String date){
this.date = date;
}
public void setAction(String action){
this.action = action;
}
public void setResult(String result){
this.result = result;
}
public void setImpact(String impact){
this.impact = impact;
}
}
这是来自 firebase 的 json 数据表:
- appname-1234b
- users
- WRQK8Fo3TPUnZyPXYnQ9gHVfFms2
- bullets
- Kfc8jCy5f2bb1aN-o0C
- bullet
action: "did some stuff"
date: "19 Mar 2017"
impact: "some stuff was impacted"
orderDate: "2017078"
result: "a result happened"
title: "new one for the date"
- KfcMg-7-xp98Kwq-PUR
- bullet
action: "did some stuff"
date: "19 Mar 2017"
impact: "some stuff was impacted"
orderDate: "2017078"
result: "a result happened"
title: "new one for the date"
当我运行调试器时,当它到达 Bullet bullet = snapshot.getValue(Bullet.class);
,我可以看到所有看起来像 Bullet: snapshot {key: Kfc8jCy5f2bb1aN-o0C title:"new one for the date" date:"19 Mar 2017"......}
的数据点,但是当它到达下两行时
String date = bullet.getDate();
String title = bullet.getTitle();
调试器将值显示为 date = null bullet:3248b
和 title = null bullet:3248b
我尝试了许多不同的方法来提取数据:
String date = snapshot.getValue(Bullet.Class).getDate();
String textBullet = snapshot.getValue(Bullet.Class).toString();
但每次出现空值或具有不可提取的全部项目符号数据时。
原文由 IamKlutch 发布,翻译遵循 CC BY-SA 4.0 许可协议
您在每个推送 ID 下都有一个名为
bullet
的孩子,但您没有在听众中考虑到这一点。最简单的解决方案是跳过代码中的
bullet
节点:但更好的解决方案是将您的数据结构更改为不具有
bullet
级别。如果您没有在代码中使用它,那么在您的数据库中就没有用。