Surekha
Surekha

Reputation: 343

How to get particular key value from firebase data?

{
  "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"
  }
}

How to get DIV_ID? Initially i need to compare key(Ex::Here DIV_10) and then DIV_NAME need to be get. Thanks in advance...

Upvotes: 3

Views: 6332

Answers (1)

koceeng
koceeng

Reputation: 2163

I assume parent of DIV_1 and DIV_10 is root. If you have value of DIV_ID like "1" or "10" and need to get value of DIV_NAME, then you should do it like this:

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
             }
        }
        ...
    }

But if you have key value like DIV_1 or DIV_10 then it should be lot easier. Like this:

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
        }
        ...
    }

Hope this helps

Upvotes: 5

Related Questions