在Firestore数据库中访问存储为Object的数据

时间:2017-10-23 09:01:08

标签: android firebase google-cloud-firestore

database structure

最近我开始测试Firebase新文档db Firestore用于学习目的,我现在卡在文档中作为对象访问值存储。

我使用以下代码访问存储在文档中的对象Privacy,但我不确定如何访问Key - Value?例如,对象中有3个子Key - Value对,我将如何单独访问和编辑它?

DocumentReference docRef = FirebaseFirestore.getInstance().collection("Users").document("PQ8QUHno6QdPwM89DsVTItrHGWJ3");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData().get("privacy"));
                Object meta_object = task.getResult().getData().get("privacy");
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:8)

您文档中的privacy字段可以被视为Map<String, Boolean>,因此您可以将此字段的值转换为这样的变量:

HashMap<String, Boolean> privacy = (HashMap<String, Boolean>) task.getResult().getData().get("privacy");

现在主要的问题是您可能会看到"unchecked cast" compiler warning,因为像这样投射Map并不理想,因为您无法保证数据库结构始终包含{{ 1}}此字段中的值。

在这种情况下,我建议使用custom objects to store&amp;数据库中的retrieve objects,它将自动为您处理编组和转换:

String : Boolean

您的DocumentReference docRef = FirebaseFirestore.getInstance().collection("Users").document("PQ8QUHno6QdPwM89DsVTItrHGWJ3"); docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { DocumentSnapshot document = task.getResult(); if (document != null) { User user = task.getResult().toObject(User.class); } else { Log.d(TAG, "No such document"); } } else { Log.d(TAG, "get failed with ", task.getException()); } } }); 课程类似于:

User

在此示例中,public class User { private String username; private HashMap<String, Boolean> privacy; public User() {} public User(String username, HashMap<String, Boolean> privacy) { this.username = username; this.privacy = privacy; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public HashMap<String, Boolean> getPrivacy() { return username; } public void setPrivacy(HashMap<String, Boolean> privacy) { this.privacy = privacy; } } 调用会将整个文档编组到您的User user = task.getResult().toObject(User.class)对象的实例中,然后您可以使用以下命令访问隐私地图:

User

文档中的每个字段都将与自定义对象中具有相同名称的字段匹配,因此您也可以以相同的方式添加HashMap<String, Boolean> userPrivacy = user.getPrivacy(); settings字段。你只需要记住:

  

每个自定义类必须具有不带参数的公共构造函数。此外,该类必须包含每个属性的公共getter。