简体   繁体   中英

Firebase - How to retrieve the ID of a database item?

I've set up a simple database which holds questions and answers to those questions. Pretty simple, just 5 strings and that's it. Here's the code:

questions
 -KbFaJVwP1HKu-rHfrjT
     ans1: 
        "test"
     ans2: 
        "1"
     ans3: 
        "2"
     ans4: 
        "3"
     question: 
        "Testing"
 -KbFlP8A08y2k4Vp1XET
     ans1: 
        "test"
     ans2: 
        "test2"
     ans3: 
        "test3"
     ans4: 
        "test4"
     question: 
        "Testing"

I've submitted two entries just to test it out, but what I'm wondering is how do I return the IDs of these questions? I need a unique identifier, which in these cases is KbFaJVwP1HKu-rHfrjT and KbFlP8A08y2k4Vp1XET , but using the getKey method, I'm getting the "question" as a result, because it is set as a primary key.

How do I work around this issue? Is my database set up improperly?

If you get question when calling getKey() , you can iterate through the children with:

for( DataSnapshot child : dataSnapshot.getChildren() ) {
    String childKey = child.getKey();
    ...
}

This will loop twice, where childKey will be -KbFaJVwP1HKu-rHfrjT and -KbFlP8A08y2k4Vp1XET

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