使用Firebase Android中的键从Datasnapshot对象获取值

时间:2016-12-13 12:21:09

标签: android firebase firebase-realtime-database

我想从DataSnapShot对象获取后打印一些数据。为了打印它,我正在这样做;

private void getUpdates(DataSnapshot DS){
    for(DataSnapshot mydata:DS.getChildren()){
     Log.i("", String.valueOf(data));
    }
}

并将firebase实例设为;

       FirebaseDatabase database = FirebaseDatabase.getInstance();
        myRef = database.getReference("myDB");
        myRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                getUpdates(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                getUpdates(dataSnapshot);
            }

打印为:

 DataSnapshot { key = areaName, value = myName1}
    DataSnapshot { key = decs, value =  desc1}
    DataSnapshot { key = areaName, value = myName2 }
    DataSnapshot { key = desc, value = desc2 }

但是我想只获得desc个值。

我的模型类是:

public class Singleton {
    private String areaName;
    private String desc;


    public Singleton(String areaName, String desc) {
        this.areaName = areaName;
        this.desc = desc;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }



}

我试过这种方式;

String decsrip= (String) mydata.child("desc").getValue();
Log.i("", decsrip);

但它正在打印

null

然后我尝试了

Map<String, Object> map = (Map<String, Object>) mydata.getValue();
String descrip = (String) map.get("desc");
Log.i("",descrip );

应用程序崩溃说

  

java.lang.ClassCastException:java.lang.String无法强制转换为java.util.Map

数据在哪里?我可以仅获得desc的值吗?

1 个答案:

答案 0 :(得分:3)

你唯一需要做的就是

FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("myDB");
myRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Singleton data = dataSnapshot.getValue(Singleton.class);
        Log.i("", String.valueOf(data.getDesc()));
    }

    ...
}

您还需要在Singleton模型中添加一个空构造函数。

public class Singleton {
  private String areaName;
  private String desc;

  public Singleton() {
  }

  public Singleton(String areaName, String desc) {
    this.areaName = areaName;
    this.desc = desc;
  }

  public String getAreaName() {
    return areaName;
  }

  public void setAreaName(String areaName) {
    this.areaName = areaName;
  }

  public String getDesc() {
    return desc;
  }

  public void setDesc(String desc) {
    this.desc = desc;
  }
}