首页 > 解决方案 > 嵌套数据firebase的嵌套类

问题描述

假设我正在为这些数据编写类:

firebase 中的数据

    reliclistener = mydb.child("relics").addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


                for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                    Log.d("inside",childSnapshot.getValue().toString());


                    relics.put(childSnapshot.getKey(), childSnapshot.getValue(Relic.class));
                    Log.d("insiderelic",relics.get(childSnapshot.getKey()).getDrop().getName()); //not workin
                }
    }
});

有一张文物地图采用文物类对象。

childSnapshot.getKey()).getDrop().getName() 一片空白

这是 Relic 类:

public class Relic {
  public Double latitude;
  public Double longitude;
  public Drop mydrop;

  public Relic() {}

  public Double getLatitude() {
    return latitude;
  }
  public Double getLongitude() {
    return longitude;
  }

  public Drop getDrop() {
    return mydrop;
  }

  public static class Drop {

    String name;
    int count;

    Drop() {

    } 

    public String getName() {
      return name;
    }
    public int getCount() {
      return count;
    }
  }
}

Log.d 里面的结果:

{latitude=0, longitude=0, drop={name=test, count=1}}

{latitude=40.8923772, longitude=29.3805392, drop={name=qwew, count=20}}

另一个问题是,如果数据的结构如下:

drop
   0
    name:test
    count:3
   1
    name:somethng
    count:4

标签: androidfirebasefirebase-realtime-database

解决方案


重新定义你的遗物类:

public class Relic {
    private Double latitude;
    private Double longitude;
    private Drop drop;

    public Double getLatitude() {
        return latitude;
    }

    public void setLatitude(Double latitude) {
        this.latitude = latitude;
    }

    public Double getLongitude() {
        return longitude;
    }

    public void setLongitude(Double longitude) {
        this.longitude = longitude;
    }

    public Drop getDrop() {
        return drop;
    }

    public void setDrop(Drop drop) {
        this.drop = drop;
    }
}

还有你的降级:

public class Drop {

    private String name;
    private int count;

    public String getName() {
        return name;
    }

    public int getCount() {
        return count;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

现在你可以这样做:

 for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
             Relic relic = childSnapshot.getValue(Relic.class);

  }

如果你想要一个掉落列表(第二个问题),只需像这样定义你的遗物类:

public class Relic {
    private List<Drop> drop;
   ...
   }

推荐阅读