【问题标题】:How to work with list of data in firebase firestore android如何使用firebase firestore android中的数据列表
【发布时间】:2019-06-15 06:37:07
【问题描述】:

我正在使用 Firebase Firestore,因为我希望收集的所有文档都显示在我的 RecyclerView 中。我可以使用此代码获取数据。

 db.collection("resturant_profile").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful()){

                    for(DocumentSnapshot documentSnapshot:task.getResult()){
                        Log.d("amit",documentSnapshot.getId()+" => "+documentSnapshot.getData());


                    }

                }
            }
        });

但我现在不知道如何通过制作类来分别获取列表的每个数据。我想我应该使用方法

documentSnapshot.toObject(someclass);

现在我不知道该用什么类型的类。

我阅读了文档,但没有找到解决方案。

【问题讨论】:

    标签: java android firebase google-cloud-firestore


    【解决方案1】:

    使用您希望在文档中使用的相同字段名称创建模型类,例如:

    public class Restaurant{
    
    String title, desc;
    
    public Restaurant(){}
    
    public Restaurant(String title, String desc) {
            this.title = title;
            this.desc  = desc;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    
    } 
    

    然后在获取时做:

    Restaurant res = document.toObject(Restaurant.class)
    

    【讨论】:

    • 错误答案,因为它需要 Class 作为 android studio 中显示的参数,也会出现编译错误。消息传递错误:找不到符号类 T
    • 错误是编译,日志如下:: error: cannot find symbol class T
    【解决方案2】:

    您可以通过它的键获取每个单个值,例如:

    String categoryId = snapshot.child("categoryId").getValue().toString();
    

    然后将其存储在模型对象中,例如:

    resModel.setCategoryId(categoryId);
    

    【讨论】:

    • 我们不能在 documentSnapshot 上调用子方法
    • @Mohammad:OP 正在使用 Firestore,而您答案中的语法适用于 Firebase 实时数据库。
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多