Firebase数据库无法使用dataSnapshot检索我的列表(无法转换对象)

时间:2017-03-09 17:31:38

标签: android firebase firebase-realtime-database

 public void retriveData(){
                databaseReference.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        Log.e("Count " ,""+dataSnapshot.getChildrenCount());
                        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                            Info post=new Info();
                            Log.e("EEEERRRORRR", "onChildAdded: "+postSnapshot.toString() );
                            Info post=postSnapshot.getValue(Info.class);
                            Log.e("Get Data", post.getQuestion());
                        }
                    }

这是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.sahilliolu.rqagame, PID: 3006
              com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.sahilliolu.rqagame.Info

在setQuestion()之前一切正常。我在log.e中得到了correctChildrenCont。我怎样才能解决这个问题?为了更多的参考,我粘贴了我的Info类,这是一个在构造函数

中有字符串参数的简单类
public class Info {
    public String answer,question,a,b,c,d;


    public Info(String question,String answer,String a,String b,String c,String d){
        this.question=question;
        this.a=a;
        this.b=b;
        this.c=c;
        this.d=d;
        this.answer=answer;
    }
    public Info(){

    }
    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }


}

1 个答案:

答案 0 :(得分:0)

您应该使用所需类的数据快照创建对象,如

 ClassName post = postSnapshot.getValue();

并且您的类应包含与数据库中相同的变量

ex您的数据库包含两列Name和Age

那么你的Class应该包含Name和Age作为变量,你应该创建getter,setter和constructor

通过使用此方法获取数据,您的数据(问题)将已设置为您的变量。

看到这个 for more info