简体   繁体   中英

How to retrieve a unique ID from a Firebase database?

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.

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

         });

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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM