gpt4 book ai didi

java - 无法从嵌套 Firebase 数据库获取值

转载 作者:行者123 更新时间:2023-12-02 02:22:07 24 4
gpt4 key购买 nike

我的 Firebase 数据库结构如下:

enter image description here

本质上,我试图捕捉“答案”的值(value)。我正在运行以下代码:

 public void onDataChange(DataSnapshot dataSnapshot) {
//should dump all of poll creators items in the following section of the current user
Log.v("DataSnap", dataSnapshot.toString());
Log.v("DataSnap", dataSnapshot.child(USER_ID_LABEL).getValue().toString());
ArrayList<String > mPollAnswers = new ArrayList<>();
for (DataSnapshot y : dataSnapshot.child(ANSWERS_LABEL).getChildren()){
Log.v("ANSWER", y.getValue().toString());
}

不幸的是,当我严格想要答案的值时,它同时返回“票数”和“答案”:

enter image description here

最佳答案

如果您有权访问顶级键,例如 L3l1...、“answers”和“1”,Firebase 将以 Hashmap<String, Object> 的形式返回结果对象。哪里Object可以是任何东西。

FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
firebaseDatabase.getReference("<top-level-key>")
.child("L3l1...")
.child("answers")
.child("1")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Returns a hashmap with keys of type answer and vote_count
Object value = dataSnapshot.getValue(); /
Object o = ((HashMap) value).get("answer");
String s = "";
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
  • 更优雅的解决方案为了简化事情,创建一个 Answer类并将其转换到数据快照。

    public class Answer {
    private int vote_count;
    private String answer;

    public Answer() {
    }

    public int getVote_count() {
    return vote_count;
    }

    public void setVote_count(int vote_count) {
    this.vote_count = vote_count;
    }

    public String getAnswer() {
    return answer;
    }

    public void setAnswer(String answer) {
    this.answer = answer;
    }
    }
  • 在您的 Activity 中或您调用 firebase 的任何位置:

    //In your Activity or Fragment or wherever you call Firebase
    firebaseDatabase.getReference("<top-level-key>")
    .child("L13a")
    .child("answers")
    .child("1")
    .addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

    Answer value = dataSnapshot.getValue(Answer.class);
    //value.getAnswer() = "rstrrs"
    //value.getVote_Count() = 0
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
    });

    关于java - 无法从嵌套 Firebase 数据库获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363650/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com