3
{
  "items" : {
    "Chemistry" : {
      "-KiUOPW8TR_QcEeDbrAy" : {
        "answer" : "ssssss",
        "id" : "1",
        "question" : "sss"
      }
    },
    "Countries" : {
      "-KiUR2ilBYN5LJU6uOCf" : {
        "answer" : "ffffff",
        "id" : "1",
        "question" : "fffff"
      }
    },
    "Film" : {
      "-KiUOr7GbPhV_perbHt4" : {
        "answer" : "dddd",
        "id" : "1",
        "question" : "dd"
      }
    }
}

From the above data, I want to get only child names of items.

Eg. I want to get these names

Chemistry 
Countries 
Film

How can I do that?

AL.
  • 36,815
  • 10
  • 142
  • 281
Ashique bzq
  • 541
  • 2
  • 9
  • 21
  • 10
    Possible duplicate of [How to get the key from the value in firebase](http://stackoverflow.com/questions/38232140/how-to-get-the-key-from-the-value-in-firebase) – Selvin Apr 24 '17 at 11:24
  • Please also add the *firebase-database* tag to your question. Thanks man! – Paulo Mattos Apr 24 '17 at 11:28

1 Answers1

9

To get those names, please use this code:

DatabaseReference itemsRef = FirebaseDatabase.getInstance().getReference().child("items");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.getKey();  
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
    }
};
itemsRef.addListenerForSingleValueEvent(eventListener);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193