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"
这是我的JSON Firebase数据库的示例。我需要知道的是如何检索这些唯一标识符? KbFaJVwP1HKu-rHfrjT
,KbGl_FZUr-BMACkvVh5
,KbHHX27kjH8TgoE1PwW
,KbHHX27kjH8TgoE1PwW
和KbHHX27kjH8TgoE1PwW
。
使用方法getKey
返回值只返回主键的名称,在本例中为question
,但我需要这些唯一标识符才能访问它们以供使用。
答案 0 :(得分:1)
您必须使用ChildEventListener或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) {
}
});
答案 1 :(得分:0)
这个怎么样:
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());
}
}