从Firebase检索孩子的信息回到android工作室

时间:2016-10-25 01:44:43

标签: android firebase firebase-realtime-database

我是Android Studio和Firebase的新手。我知道为了从其唯一ID获取子数据,我可能需要使用数据快照方法。例如,我需要从Firebase数据库中检索name回到android studio应用程序。在这种情况下如何实现它?非常感谢帮助!

{
  "0Zs7aiWplRRJ5IJ5pazuUOxIdqz2" : {

    "name" : "yeo",
    "pos" : "intern",
    "team" : "nwrs"
  },
  "kaLCjJFoGETWCWH42kNkc90b5Ku1" : {

    "2016" : {
      "9" : {
    "25" : {
      ".priority" : 0.0,
      "AM" : "",
      "OT" : "",
      "OVN" : "",
      "PM" : "",
      "TPT" : ""
    }
      },
      "10" : {
    "1" : {
      ".priority" : 0.0,
      "AM" : "zxc11",
      "OT" : "12",
      "OVN" : "33",
      "PM" : "222",
      "TPT" : "54"
    },
    "26" : {
      "AM" : "aa",
      "OVN" : "gg",
      "PM" : "ccc",
      "TPT" : ""
    },
    "29" : {
      ".priority" : 0.0,
      "AM" : "dd",
      "OVN" : "aa",
      "PM" : "ss",
      "TPT" : "2fd"
    }
      }
    },
    "name" : "Jing Yang",
    "pos" : "Intern",
    "team" : "NWRS"
  }
}

以下是我当前的代码

    root.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Set<String> set = new HashSet<String>();
            Iterator i = dataSnapshot.getChildren().iterator();

            while (i.hasNext()){
                set.add(((DataSnapshot)i.next()).getKey());

            }
            names.clear();
            names.addAll(set);

            arrayAdapter.notifyDataSetChanged();

1 个答案:

答案 0 :(得分:0)

我假设root指的是数据库的根。在这种情况下,您的onDataChange将获得该位置的整个数据的快照。您可以循环遍历它们并依次获取每个孩子的属性:

root.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Set<String> set = new HashSet<String>();
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            //set.add(childSnapshot.getKey());
            set.add(childSnapshot.child("name").getValue(String.class));
        }
        names.clear();
        names.addAll(set);

        arrayAdapter.notifyDataSetChanged();

但我强烈建议您创建一个表示列表中项目的Java类。在您的情况下,可以这么简单:

public class Item {
    public string name;
    public string pos;
    public string team;
}

然后您可以阅读以下项目:

root.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Set<String> set = new HashSet<String>();
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            Item child = childSnapshot.getValue(Item.class);
            set.add(item.name);
        }
        names.clear();
        names.addAll(set);

        arrayAdapter.notifyDataSetChanged();