如何从firebase数据中获取特定键值?

时间:2017-04-08 07:39:54

标签: android android-studio firebase-realtime-database

{
  "DIV_1" : {
    "ACTINACT" : 1,
    "COORDINATOR" : "10CA056",
    "DIV_CODE" : "BSL",
    "DIV_ID" : 1,
    "DIV_NAME" : "Bhusawal",
    "ERP_LOC_CODE" : "CRB",
    "MTIME" : "2017-04-08T11:02:59",
    "ZONE_ID" : "ZONE_1"
  },

  "DIV_10" : {
    "ACTINACT" : 1,
    "COORDINATOR" : "06CS011",
    "DIV_CODE" : "UMB",
    "DIV_ID" : 10,
    "DIV_NAME" : "Ambala",
    "ERP_LOC_CODE" : "NRA",
    "MTIME" : "2017-04-08T11:02:59",
    "ZONE_ID" : "ZONE_3"
  }
}

如何获得DIV_ID? 最初我需要比较密钥(Ex :: Here DIV_10)然后DIV_NAME需要得到。 提前谢谢......

1 个答案:

答案 0 :(得分:5)

我假设DIV_1和DIV_10的父级是root。如果您的DIV_ID值为“1”或“10”且需要获得DIV_NAME的值,那么您应该这样做:

int divId = 1; // sample
FirebaseDatabase.getInstance().getReference().orderByChild("DIV_ID").equalTo(divId)
    .addValueEventListener(new ValueEventListener() {
        ... onDataChange(DataSnapshot dataSnapshot) {
             for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                 String divName = snapshot.child("DIV_NAME").getValue(String.class);
                 // there you go
                 // and please check if you have more than 1 value as result
             }
        }
        ...
    }

但是如果你有像DIV_1DIV_10这样的关键值,那么它应该会容易得多。像这样:

String key = "DIV_1";
FirebaseDatabase.getInstance().getReference(key)
    .addValueEventListener(new ValueEventListener() {
        ... onDataChange(DataSnapshot dataSnapshot) {
             String divName = snapshot.child("DIV_NAME").getValue(String.class);
             // note that in this sample, it doesn't need to loop, because:
             // data you get here is one level deeper than data you got on first sample
        }
        ...
    }

希望这有帮助