如何从Firestore获取我的模型(POJO)类的对象?

时间:2018-07-26 19:37:44

标签: java firebase firebase-realtime-database google-cloud-firestore

我正在测试Firestore使其更熟悉并在我的项目中实现,但是由于某种原因,我无法从数据库中获取POJO类的对象。我知道我可以将数据作为Map获取,但我需要POJO类。我已经遵循了许多答案来帮助我入门,但是我无法解决这个问题。这是我的代码:

mDocumentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            UserPOJO pojo = (UserPOJO) task.getResult(); //Error
        }
    }
});

getResult()对我没有帮助。所以我在POJO中添加了数据,我的问题是,如何以POJO的形式取回数据?

我的POJO:

public class UserPOJO {
    private String name, email, id, college, state;
    private int age, number;

    public UserPOJO() {
    }

    public UserPOJO(String name, String email, String id, String college, String state, int age, int number) {
        this.name = name;
        this.email = email;
        this.id = id;
        this.college = college;
        this.state = state;
        this.age = age;
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

我的错误:

错误:类型不兼容:DocumentSnapshot无法转换为UserPOJO

1 个答案:

答案 0 :(得分:0)

UserPOJO对象上调用getResult()方法时,无法获得task对象,因为它永远不会返回这样的对象,它将返回一个DocumentSnapshot对象。即使将其强制转换为UserPOJO对象,它也完全无法帮助您。 Java中无法将DocumentSnapshot对象投射到UserPOJO,因为它们之间没有关系。

official documentation,这是从数据库取回UserPOJO类的对象的方法:

mDocumentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                //Get an object of type UserPOJO
                UserPOJO pojo = document.toObject(UserPOJO.class);
            }
        }
    }
});

请参见,解决此问题的关键是使用DocumentSnapshot.toObject()'s方法。