3
survey-6d90daddclose
 questions
 -KbFaJVwP1HKu-rHfrjT
     ans1: 
        "test"
     ans2: 
        "1"
     ans3: 
        "2"
     ans4: 
        "3"
     question: 
        "Testing"
 -KbFlP8A08y2k4Vp1XET
     ans1: 
        "test"
     ans2: 
        "test2"
     ans3: 
        "test3"
     ans4: 
        "test4"
     question: 
        "Testing"
 -KbGl_FZUr-BMACkvVh5
     ans1: 
        "aopskdpoaskd"
     ans2: 
        "askdaksd"
     ans3: 
        "aospkdpoaskd"
     ans4: 
        "alksdlaksd"
     question: 
        "aoskdpoaskd"
 -KbHHX27kjH8TgoE1PwW
     ans1: 
        "asdasd"
     ans2: 
        "asdasd"
     ans3: 
        "asdasd"
     ans4: 
        "asdasd"
     question: 
        "asdasd"
 -KbHHxHoh7_yiBcvXU0-
     ans1: 
        "asdasd"
     ans2: 
        "asdasd"
     ans3: 
        "asdasd"
     ans4: 
        "asdasdasd"
     question: 
        "questions"

This is a sample of my JSON Firebase database. What I need to know is how I can retrieve these unique identifiers? KbFaJVwP1HKu-rHfrjT, KbGl_FZUr-BMACkvVh5, KbHHX27kjH8TgoE1PwW, KbHHX27kjH8TgoE1PwW and KbHHX27kjH8TgoE1PwW.

Returning the values using method getKey only returns the name of the primary key, which in this case is question, but I need these unique identifiers to be able to access them for use.

user1938007
  • 459
  • 1
  • 5
  • 14

2 Answers2

1

You have to use a ChildEventListener or a ValueEventListener:

DatabaseReference ref=FirebaseDatabase.getInstace().getReference().child("questions");





    ref.addListenerForSingleValueEvent(new ValueEventListener() {
         @Override 
        public void onDataChange(DataSnapshot dataSnapshot)
         { for (DataSnapshot questionSnapshot : dataSnapshot.getChildren()) { 
//The key of the question
        String questionKey = questionSnapshot.getKey();
//And if you want to access the rest:
String ans1 = questionSnapshot.child("ans1").getValue(String.class);
    } 

        } 

        @Override
     public void onCancelled(DatabaseError databaseError) { 
}

         });
Hhorn
  • 223
  • 2
  • 6
0

How about this:

new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot child : dataSnapshot.getChildren()) { 
                 //Get keys individually.      
                 child.getKey(); 
            }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.out.println("The read failed: " + databaseError.getCode());
    }
}